diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2786f9b7b90e5330c97d52858b37707de46d31f9
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/__init__.py
@@ -0,0 +1,1579 @@
+"""
+An object-oriented plotting library.
+
+A procedural interface is provided by the companion pyplot module,
+which may be imported directly, e.g.::
+
+ import matplotlib.pyplot as plt
+
+or using ipython::
+
+ ipython
+
+at your terminal, followed by::
+
+ In [1]: %matplotlib
+ In [2]: import matplotlib.pyplot as plt
+
+at the ipython shell prompt.
+
+For the most part, direct use of the explicit object-oriented library is
+encouraged when programming; the implicit pyplot interface is primarily for
+working interactively. The exceptions to this suggestion are the pyplot
+functions `.pyplot.figure`, `.pyplot.subplot`, `.pyplot.subplots`, and
+`.pyplot.savefig`, which can greatly simplify scripting. See
+:ref:`api_interfaces` for an explanation of the tradeoffs between the implicit
+and explicit interfaces.
+
+Modules include:
+
+:mod:`matplotlib.axes`
+ The `~.axes.Axes` class. Most pyplot functions are wrappers for
+ `~.axes.Axes` methods. The axes module is the highest level of OO
+ access to the library.
+
+:mod:`matplotlib.figure`
+ The `.Figure` class.
+
+:mod:`matplotlib.artist`
+ The `.Artist` base class for all classes that draw things.
+
+:mod:`matplotlib.lines`
+ The `.Line2D` class for drawing lines and markers.
+
+:mod:`matplotlib.patches`
+ Classes for drawing polygons.
+
+:mod:`matplotlib.text`
+ The `.Text` and `.Annotation` classes.
+
+:mod:`matplotlib.image`
+ The `.AxesImage` and `.FigureImage` classes.
+
+:mod:`matplotlib.collections`
+ Classes for efficient drawing of groups of lines or polygons.
+
+:mod:`matplotlib.colors`
+ Color specifications and making colormaps.
+
+:mod:`matplotlib.cm`
+ Colormaps, and the `.ScalarMappable` mixin class for providing color
+ mapping functionality to other classes.
+
+:mod:`matplotlib.ticker`
+ Calculation of tick mark locations and formatting of tick labels.
+
+:mod:`matplotlib.backends`
+ A subpackage with modules for various GUI libraries and output formats.
+
+The base matplotlib namespace includes:
+
+`~matplotlib.rcParams`
+ Default configuration settings; their defaults may be overridden using
+ a :file:`matplotlibrc` file.
+
+`~matplotlib.use`
+ Setting the Matplotlib backend. This should be called before any
+ figure is created, because it is not possible to switch between
+ different GUI backends after that.
+
+The following environment variables can be used to customize the behavior:
+
+:envvar:`MPLBACKEND`
+ This optional variable can be set to choose the Matplotlib backend. See
+ :ref:`what-is-a-backend`.
+
+:envvar:`MPLCONFIGDIR`
+ This is the directory used to store user customizations to
+ Matplotlib, as well as some caches to improve performance. If
+ :envvar:`MPLCONFIGDIR` is not defined, :file:`{HOME}/.config/matplotlib`
+ and :file:`{HOME}/.cache/matplotlib` are used on Linux, and
+ :file:`{HOME}/.matplotlib` on other platforms, if they are
+ writable. Otherwise, the Python standard library's `tempfile.gettempdir`
+ is used to find a base directory in which the :file:`matplotlib`
+ subdirectory is created.
+
+Matplotlib was initially written by John D. Hunter (1968-2012) and is now
+developed and maintained by a host of others.
+
+Occasionally the internal documentation (python docstrings) will refer
+to MATLABĀ®, a registered trademark of The MathWorks, Inc.
+
+"""
+
+__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",
+ "multivar_colormaps",
+ "bivar_colormaps",
+ "color_sequences",
+]
+
+
+import atexit
+from collections import namedtuple
+from collections.abc import MutableMapping
+import contextlib
+import functools
+import importlib
+import inspect
+from inspect import Parameter
+import locale
+import logging
+import os
+from pathlib import Path
+import pprint
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+
+from packaging.version import parse as parse_version
+
+# cbook must import matplotlib only within function
+# definitions, so it is safe to import from it here.
+from . import _api, _version, cbook, _docstring, rcsetup
+from matplotlib._api import MatplotlibDeprecationWarning
+from matplotlib.rcsetup import cycler # noqa: F401
+
+
+_log = logging.getLogger(__name__)
+
+__bibtex__ = r"""@Article{Hunter:2007,
+ Author = {Hunter, J. D.},
+ Title = {Matplotlib: A 2D graphics environment},
+ Journal = {Computing in Science \& Engineering},
+ Volume = {9},
+ Number = {3},
+ Pages = {90--95},
+ abstract = {Matplotlib is a 2D graphics package used for Python
+ for application development, interactive scripting, and
+ publication-quality image generation across user
+ interfaces and operating systems.},
+ publisher = {IEEE COMPUTER SOC},
+ year = 2007
+}"""
+
+# modelled after sys.version_info
+_VersionInfo = namedtuple('_VersionInfo',
+ 'major, minor, micro, releaselevel, serial')
+
+
+def _parse_to_version_info(version_str):
+ """
+ Parse a version string to a namedtuple analogous to sys.version_info.
+
+ See:
+ https://packaging.pypa.io/en/latest/version.html#packaging.version.parse
+ https://docs.python.org/3/library/sys.html#sys.version_info
+ """
+ v = parse_version(version_str)
+ if v.pre is None and v.post is None and v.dev is None:
+ return _VersionInfo(v.major, v.minor, v.micro, 'final', 0)
+ elif v.dev is not None:
+ return _VersionInfo(v.major, v.minor, v.micro, 'alpha', v.dev)
+ elif v.pre is not None:
+ releaselevel = {
+ 'a': 'alpha',
+ 'b': 'beta',
+ 'rc': 'candidate'}.get(v.pre[0], 'alpha')
+ return _VersionInfo(v.major, v.minor, v.micro, releaselevel, v.pre[1])
+ else:
+ # fallback for v.post: guess-next-dev scheme from setuptools_scm
+ return _VersionInfo(v.major, v.minor, v.micro + 1, 'alpha', v.post)
+
+
+def _get_version():
+ """Return the version string used for __version__."""
+ # Only shell out to a git subprocess if really needed, i.e. when we are in
+ # a matplotlib git repo but not in a shallow clone, such as those used by
+ # CI, as the latter would trigger a warning from setuptools_scm.
+ root = Path(__file__).resolve().parents[2]
+ if ((root / ".matplotlib-repo").exists()
+ and (root / ".git").exists()
+ and not (root / ".git/shallow").exists()):
+ try:
+ import setuptools_scm
+ except ImportError:
+ pass
+ else:
+ return setuptools_scm.get_version(
+ root=root,
+ dist_name="matplotlib",
+ version_scheme="release-branch-semver",
+ local_scheme="node-and-date",
+ fallback_version=_version.version,
+ )
+ # Get the version from the _version.py file if not in repo or setuptools_scm is
+ # unavailable.
+ return _version.version
+
+
+@_api.caching_module_getattr
+class __getattr__:
+ __version__ = property(lambda self: _get_version())
+ __version_info__ = property(
+ lambda self: _parse_to_version_info(self.__version__))
+
+
+def _check_versions():
+
+ # Quickfix to ensure Microsoft Visual C++ redistributable
+ # DLLs are loaded before importing kiwisolver
+ from . import ft2font # noqa: F401
+
+ for modname, minver in [
+ ("cycler", "0.10"),
+ ("dateutil", "2.7"),
+ ("kiwisolver", "1.3.1"),
+ ("numpy", "1.23"),
+ ("pyparsing", "2.3.1"),
+ ]:
+ module = importlib.import_module(modname)
+ if parse_version(module.__version__) < parse_version(minver):
+ raise ImportError(f"Matplotlib requires {modname}>={minver}; "
+ f"you have {module.__version__}")
+
+
+_check_versions()
+
+
+# The decorator ensures this always returns the same handler (and it is only
+# attached once).
+@functools.cache
+def _ensure_handler():
+ """
+ The first time this function is called, attach a `StreamHandler` using the
+ same format as `logging.basicConfig` to the Matplotlib root logger.
+
+ Return this handler every time this function is called.
+ """
+ handler = logging.StreamHandler()
+ handler.setFormatter(logging.Formatter(logging.BASIC_FORMAT))
+ _log.addHandler(handler)
+ return handler
+
+
+def set_loglevel(level):
+ """
+ Configure Matplotlib's logging levels.
+
+ Matplotlib uses the standard library `logging` framework under the root
+ logger 'matplotlib'. This is a helper function to:
+
+ - set Matplotlib's root logger level
+ - set the root logger handler's level, creating the handler
+ if it does not exist yet
+
+ Typically, one should call ``set_loglevel("info")`` or
+ ``set_loglevel("debug")`` to get additional debugging information.
+
+ Users or applications that are installing their own logging handlers
+ may want to directly manipulate ``logging.getLogger('matplotlib')`` rather
+ than use this function.
+
+ Parameters
+ ----------
+ level : {"notset", "debug", "info", "warning", "error", "critical"}
+ The log level of the handler.
+
+ Notes
+ -----
+ The first time this function is called, an additional handler is attached
+ to Matplotlib's root handler; this handler is reused every time and this
+ function simply manipulates the logger and handler's level.
+
+ """
+ _log.setLevel(level.upper())
+ _ensure_handler().setLevel(level.upper())
+
+
+def _logged_cached(fmt, func=None):
+ """
+ Decorator that logs a function's return value, and memoizes that value.
+
+ After ::
+
+ @_logged_cached(fmt)
+ def func(): ...
+
+ the first call to *func* will log its return value at the DEBUG level using
+ %-format string *fmt*, and memoize it; later calls to *func* will directly
+ return that value.
+ """
+ if func is None: # Return the actual decorator.
+ return functools.partial(_logged_cached, fmt)
+
+ called = False
+ ret = None
+
+ @functools.wraps(func)
+ def wrapper(**kwargs):
+ nonlocal called, ret
+ if not called:
+ ret = func(**kwargs)
+ called = True
+ _log.debug(fmt, ret)
+ return ret
+
+ return wrapper
+
+
+_ExecInfo = namedtuple("_ExecInfo", "executable raw_version version")
+
+
+class ExecutableNotFoundError(FileNotFoundError):
+ """
+ Error raised when an executable that Matplotlib optionally
+ depends on can't be found.
+ """
+ pass
+
+
+@functools.cache
+def _get_executable_info(name):
+ """
+ Get the version of some executable that Matplotlib optionally depends on.
+
+ .. warning::
+ The list of executables that this function supports is set according to
+ Matplotlib's internal needs, and may change without notice.
+
+ Parameters
+ ----------
+ name : str
+ The executable to query. The following values are currently supported:
+ "dvipng", "gs", "inkscape", "magick", "pdftocairo", "pdftops". This
+ list is subject to change without notice.
+
+ Returns
+ -------
+ tuple
+ A namedtuple with fields ``executable`` (`str`) and ``version``
+ (`packaging.Version`, or ``None`` if the version cannot be determined).
+
+ Raises
+ ------
+ ExecutableNotFoundError
+ If the executable is not found or older than the oldest version
+ supported by Matplotlib. For debugging purposes, it is also
+ possible to "hide" an executable from Matplotlib by adding it to the
+ :envvar:`_MPLHIDEEXECUTABLES` environment variable (a comma-separated
+ list), which must be set prior to any calls to this function.
+ ValueError
+ If the executable is not one that we know how to query.
+ """
+
+ def impl(args, regex, min_ver=None, ignore_exit_code=False):
+ # Execute the subprocess specified by args; capture stdout and stderr.
+ # Search for a regex match in the output; if the match succeeds, the
+ # first group of the match is the version.
+ # Return an _ExecInfo if the executable exists, and has a version of
+ # at least min_ver (if set); else, raise ExecutableNotFoundError.
+ try:
+ output = subprocess.check_output(
+ args, stderr=subprocess.STDOUT,
+ text=True, errors="replace", timeout=30)
+ except subprocess.CalledProcessError as _cpe:
+ if ignore_exit_code:
+ output = _cpe.output
+ else:
+ raise ExecutableNotFoundError(str(_cpe)) from _cpe
+ except subprocess.TimeoutExpired as _te:
+ msg = f"Timed out running {cbook._pformat_subprocess(args)}"
+ raise ExecutableNotFoundError(msg) from _te
+ except OSError as _ose:
+ raise ExecutableNotFoundError(str(_ose)) from _ose
+ match = re.search(regex, output)
+ if match:
+ raw_version = match.group(1)
+ version = parse_version(raw_version)
+ if min_ver is not None and version < parse_version(min_ver):
+ raise ExecutableNotFoundError(
+ f"You have {args[0]} version {version} but the minimum "
+ f"version supported by Matplotlib is {min_ver}")
+ return _ExecInfo(args[0], raw_version, version)
+ else:
+ raise ExecutableNotFoundError(
+ f"Failed to determine the version of {args[0]} from "
+ f"{' '.join(args)}, which output {output}")
+
+ if name in os.environ.get("_MPLHIDEEXECUTABLES", "").split(","):
+ raise ExecutableNotFoundError(f"{name} was hidden")
+
+ if name == "dvipng":
+ return impl(["dvipng", "-version"], "(?m)^dvipng(?: .*)? (.+)", "1.6")
+ elif name == "gs":
+ execs = (["gswin32c", "gswin64c", "mgs", "gs"] # "mgs" for miktex.
+ if sys.platform == "win32" else
+ ["gs"])
+ for e in execs:
+ try:
+ return impl([e, "--version"], "(.*)", "9")
+ except ExecutableNotFoundError:
+ pass
+ message = "Failed to find a Ghostscript installation"
+ raise ExecutableNotFoundError(message)
+ elif name == "inkscape":
+ try:
+ # Try headless option first (needed for Inkscape version < 1.0):
+ return impl(["inkscape", "--without-gui", "-V"],
+ "Inkscape ([^ ]*)")
+ except ExecutableNotFoundError:
+ pass # Suppress exception chaining.
+ # If --without-gui is not accepted, we may be using Inkscape >= 1.0 so
+ # try without it:
+ return impl(["inkscape", "-V"], "Inkscape ([^ ]*)")
+ elif name == "magick":
+ if sys.platform == "win32":
+ # Check the registry to avoid confusing ImageMagick's convert with
+ # Windows's builtin convert.exe.
+ import winreg
+ binpath = ""
+ for flag in [0, winreg.KEY_WOW64_32KEY, winreg.KEY_WOW64_64KEY]:
+ try:
+ with winreg.OpenKeyEx(
+ winreg.HKEY_LOCAL_MACHINE,
+ r"Software\Imagemagick\Current",
+ 0, winreg.KEY_QUERY_VALUE | flag) as hkey:
+ binpath = winreg.QueryValueEx(hkey, "BinPath")[0]
+ except OSError:
+ pass
+ path = None
+ if binpath:
+ for name in ["convert.exe", "magick.exe"]:
+ candidate = Path(binpath, name)
+ if candidate.exists():
+ path = str(candidate)
+ break
+ if path is None:
+ raise ExecutableNotFoundError(
+ "Failed to find an ImageMagick installation")
+ else:
+ path = "convert"
+ info = impl([path, "--version"], r"^Version: ImageMagick (\S*)")
+ if info.raw_version == "7.0.10-34":
+ # https://github.com/ImageMagick/ImageMagick/issues/2720
+ raise ExecutableNotFoundError(
+ f"You have ImageMagick {info.version}, which is unsupported")
+ return info
+ elif name == "pdftocairo":
+ return impl(["pdftocairo", "-v"], "pdftocairo version (.*)")
+ elif name == "pdftops":
+ info = impl(["pdftops", "-v"], "^pdftops version (.*)",
+ ignore_exit_code=True)
+ if info and not (
+ 3 <= info.version.major or
+ # poppler version numbers.
+ parse_version("0.9") <= info.version < parse_version("1.0")):
+ raise ExecutableNotFoundError(
+ f"You have pdftops version {info.version} but the minimum "
+ f"version supported by Matplotlib is 3.0")
+ return info
+ else:
+ raise ValueError(f"Unknown executable: {name!r}")
+
+
+def _get_xdg_config_dir():
+ """
+ Return the XDG configuration directory, according to the XDG base
+ directory spec:
+
+ https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
+ """
+ return os.environ.get('XDG_CONFIG_HOME') or str(Path.home() / ".config")
+
+
+def _get_xdg_cache_dir():
+ """
+ Return the XDG cache directory, according to the XDG base directory spec:
+
+ https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
+ """
+ return os.environ.get('XDG_CACHE_HOME') or str(Path.home() / ".cache")
+
+
+def _get_config_or_cache_dir(xdg_base_getter):
+ configdir = os.environ.get('MPLCONFIGDIR')
+ if configdir:
+ configdir = Path(configdir)
+ elif sys.platform.startswith(('linux', 'freebsd')):
+ # Only call _xdg_base_getter here so that MPLCONFIGDIR is tried first,
+ # as _xdg_base_getter can throw.
+ configdir = Path(xdg_base_getter(), "matplotlib")
+ else:
+ configdir = Path.home() / ".matplotlib"
+ # Resolve the path to handle potential issues with inaccessible symlinks.
+ configdir = configdir.resolve()
+ try:
+ configdir.mkdir(parents=True, exist_ok=True)
+ except OSError as exc:
+ _log.warning("mkdir -p failed for path %s: %s", configdir, exc)
+ else:
+ if os.access(str(configdir), os.W_OK) and configdir.is_dir():
+ return str(configdir)
+ _log.warning("%s is not a writable directory", configdir)
+ # If the config or cache directory cannot be created or is not a writable
+ # directory, create a temporary one.
+ try:
+ tmpdir = tempfile.mkdtemp(prefix="matplotlib-")
+ except OSError as exc:
+ raise OSError(
+ f"Matplotlib requires access to a writable cache directory, but there "
+ f"was an issue with the default path ({configdir}), and a temporary "
+ f"directory could not be created; set the MPLCONFIGDIR environment "
+ f"variable to a writable directory") from exc
+ os.environ["MPLCONFIGDIR"] = tmpdir
+ atexit.register(shutil.rmtree, tmpdir)
+ _log.warning(
+ "Matplotlib created a temporary cache directory at %s because there was "
+ "an issue with the default path (%s); it is highly recommended to set the "
+ "MPLCONFIGDIR environment variable to a writable directory, in particular to "
+ "speed up the import of Matplotlib and to better support multiprocessing.",
+ tmpdir, configdir)
+ return tmpdir
+
+
+@_logged_cached('CONFIGDIR=%s')
+def get_configdir():
+ """
+ Return the string path of the configuration directory.
+
+ The directory is chosen as follows:
+
+ 1. If the MPLCONFIGDIR environment variable is supplied, choose that.
+ 2. On Linux, follow the XDG specification and look first in
+ ``$XDG_CONFIG_HOME``, if defined, or ``$HOME/.config``. On other
+ platforms, choose ``$HOME/.matplotlib``.
+ 3. If the chosen directory exists and is writable, use that as the
+ configuration directory.
+ 4. Else, create a temporary directory, and use it as the configuration
+ directory.
+ """
+ return _get_config_or_cache_dir(_get_xdg_config_dir)
+
+
+@_logged_cached('CACHEDIR=%s')
+def get_cachedir():
+ """
+ Return the string path of the cache directory.
+
+ The procedure used to find the directory is the same as for
+ `get_configdir`, except using ``$XDG_CACHE_HOME``/``$HOME/.cache`` instead.
+ """
+ return _get_config_or_cache_dir(_get_xdg_cache_dir)
+
+
+@_logged_cached('matplotlib data path: %s')
+def get_data_path():
+ """Return the path to Matplotlib data."""
+ return str(Path(__file__).with_name("mpl-data"))
+
+
+def matplotlib_fname():
+ """
+ Get the location of the config file.
+
+ The file location is determined in the following order
+
+ - ``$PWD/matplotlibrc``
+ - ``$MATPLOTLIBRC`` if it is not a directory
+ - ``$MATPLOTLIBRC/matplotlibrc``
+ - ``$MPLCONFIGDIR/matplotlibrc``
+ - On Linux,
+ - ``$XDG_CONFIG_HOME/matplotlib/matplotlibrc`` (if ``$XDG_CONFIG_HOME``
+ is defined)
+ - or ``$HOME/.config/matplotlib/matplotlibrc`` (if ``$XDG_CONFIG_HOME``
+ is not defined)
+ - On other platforms,
+ - ``$HOME/.matplotlib/matplotlibrc`` if ``$HOME`` is defined
+ - Lastly, it looks in ``$MATPLOTLIBDATA/matplotlibrc``, which should always
+ exist.
+ """
+
+ def gen_candidates():
+ # rely on down-stream code to make absolute. This protects us
+ # from having to directly get the current working directory
+ # which can fail if the user has ended up with a cwd that is
+ # non-existent.
+ yield 'matplotlibrc'
+ try:
+ matplotlibrc = os.environ['MATPLOTLIBRC']
+ except KeyError:
+ pass
+ else:
+ yield matplotlibrc
+ yield os.path.join(matplotlibrc, 'matplotlibrc')
+ yield os.path.join(get_configdir(), 'matplotlibrc')
+ yield os.path.join(get_data_path(), 'matplotlibrc')
+
+ for fname in gen_candidates():
+ if os.path.exists(fname) and not os.path.isdir(fname):
+ return fname
+
+ raise RuntimeError("Could not find matplotlibrc file; your Matplotlib "
+ "install is broken")
+
+
+# rcParams deprecated and automatically mapped to another key.
+# Values are tuples of (version, new_name, f_old2new, f_new2old).
+_deprecated_map = {}
+# rcParams deprecated; some can manually be mapped to another key.
+# Values are tuples of (version, new_name_or_None).
+_deprecated_ignore_map = {}
+# rcParams deprecated; can use None to suppress warnings; remain actually
+# listed in the rcParams.
+# Values are tuples of (version,)
+_deprecated_remain_as_none = {}
+
+
+@_docstring.Substitution(
+ "\n".join(map("- {}".format, sorted(rcsetup._validators, key=str.lower)))
+)
+class RcParams(MutableMapping, dict):
+ """
+ A dict-like key-value store for config parameters, including validation.
+
+ Validating functions are defined and associated with rc parameters in
+ :mod:`matplotlib.rcsetup`.
+
+ The list of rcParams is:
+
+ %s
+
+ See Also
+ --------
+ :ref:`customizing-with-matplotlibrc-files`
+ """
+
+ validate = rcsetup._validators
+
+ # validate values on the way in
+ def __init__(self, *args, **kwargs):
+ self.update(*args, **kwargs)
+
+ def _set(self, key, val):
+ """
+ Directly write data bypassing deprecation and validation logic.
+
+ Notes
+ -----
+ As end user or downstream library you almost always should use
+ ``rcParams[key] = val`` and not ``_set()``.
+
+ There are only very few special cases that need direct data access.
+ These cases previously used ``dict.__setitem__(rcParams, key, val)``,
+ which is now deprecated and replaced by ``rcParams._set(key, val)``.
+
+ Even though private, we guarantee API stability for ``rcParams._set``,
+ i.e. it is subject to Matplotlib's API and deprecation policy.
+
+ :meta public:
+ """
+ dict.__setitem__(self, key, val)
+
+ def _get(self, key):
+ """
+ Directly read data bypassing deprecation, backend and validation
+ logic.
+
+ Notes
+ -----
+ As end user or downstream library you almost always should use
+ ``val = rcParams[key]`` and not ``_get()``.
+
+ There are only very few special cases that need direct data access.
+ These cases previously used ``dict.__getitem__(rcParams, key, val)``,
+ which is now deprecated and replaced by ``rcParams._get(key)``.
+
+ Even though private, we guarantee API stability for ``rcParams._get``,
+ i.e. it is subject to Matplotlib's API and deprecation policy.
+
+ :meta public:
+ """
+ return dict.__getitem__(self, key)
+
+ def _update_raw(self, other_params):
+ """
+ Directly update the data from *other_params*, bypassing deprecation,
+ backend and validation logic on both sides.
+
+ This ``rcParams._update_raw(params)`` replaces the previous pattern
+ ``dict.update(rcParams, params)``.
+
+ Parameters
+ ----------
+ other_params : dict or `.RcParams`
+ The input mapping from which to update.
+ """
+ if isinstance(other_params, RcParams):
+ other_params = dict.items(other_params)
+ dict.update(self, other_params)
+
+ def _ensure_has_backend(self):
+ """
+ Ensure that a "backend" entry exists.
+
+ Normally, the default matplotlibrc file contains *no* entry for "backend" (the
+ corresponding line starts with ##, not #; we fill in _auto_backend_sentinel
+ in that case. However, packagers can set a different default backend
+ (resulting in a normal `#backend: foo` line) in which case we should *not*
+ fill in _auto_backend_sentinel.
+ """
+ dict.setdefault(self, "backend", rcsetup._auto_backend_sentinel)
+
+ def __setitem__(self, key, val):
+ try:
+ if key in _deprecated_map:
+ version, alt_key, alt_val, inverse_alt = _deprecated_map[key]
+ _api.warn_deprecated(
+ version, name=key, obj_type="rcparam", alternative=alt_key)
+ key = alt_key
+ val = alt_val(val)
+ elif key in _deprecated_remain_as_none and val is not None:
+ version, = _deprecated_remain_as_none[key]
+ _api.warn_deprecated(version, name=key, obj_type="rcparam")
+ elif key in _deprecated_ignore_map:
+ version, alt_key = _deprecated_ignore_map[key]
+ _api.warn_deprecated(
+ version, name=key, obj_type="rcparam", alternative=alt_key)
+ return
+ elif key == 'backend':
+ if val is rcsetup._auto_backend_sentinel:
+ if 'backend' in self:
+ return
+ try:
+ cval = self.validate[key](val)
+ except ValueError as ve:
+ raise ValueError(f"Key {key}: {ve}") from None
+ self._set(key, cval)
+ except KeyError as err:
+ raise KeyError(
+ f"{key} is not a valid rc parameter (see rcParams.keys() for "
+ f"a list of valid parameters)") from err
+
+ def __getitem__(self, key):
+ if key in _deprecated_map:
+ version, alt_key, alt_val, inverse_alt = _deprecated_map[key]
+ _api.warn_deprecated(
+ version, name=key, obj_type="rcparam", alternative=alt_key)
+ return inverse_alt(self._get(alt_key))
+
+ elif key in _deprecated_ignore_map:
+ version, alt_key = _deprecated_ignore_map[key]
+ _api.warn_deprecated(
+ version, name=key, obj_type="rcparam", alternative=alt_key)
+ return self._get(alt_key) if alt_key else None
+
+ # In theory, this should only ever be used after the global rcParams
+ # has been set up, but better be safe e.g. in presence of breakpoints.
+ elif key == "backend" and self is globals().get("rcParams"):
+ val = self._get(key)
+ if val is rcsetup._auto_backend_sentinel:
+ from matplotlib import pyplot as plt
+ plt.switch_backend(rcsetup._auto_backend_sentinel)
+
+ return self._get(key)
+
+ def _get_backend_or_none(self):
+ """Get the requested backend, if any, without triggering resolution."""
+ backend = self._get("backend")
+ return None if backend is rcsetup._auto_backend_sentinel else backend
+
+ def __repr__(self):
+ class_name = self.__class__.__name__
+ indent = len(class_name) + 1
+ with _api.suppress_matplotlib_deprecation_warning():
+ repr_split = pprint.pformat(dict(self), indent=1,
+ width=80 - indent).split('\n')
+ repr_indented = ('\n' + ' ' * indent).join(repr_split)
+ return f'{class_name}({repr_indented})'
+
+ def __str__(self):
+ return '\n'.join(map('{0[0]}: {0[1]}'.format, sorted(self.items())))
+
+ def __iter__(self):
+ """Yield sorted list of keys."""
+ with _api.suppress_matplotlib_deprecation_warning():
+ yield from sorted(dict.__iter__(self))
+
+ def __len__(self):
+ return dict.__len__(self)
+
+ def find_all(self, pattern):
+ """
+ Return the subset of this RcParams dictionary whose keys match,
+ using :func:`re.search`, the given ``pattern``.
+
+ .. note::
+
+ Changes to the returned dictionary are *not* propagated to
+ the parent RcParams dictionary.
+
+ """
+ pattern_re = re.compile(pattern)
+ return RcParams((key, value)
+ for key, value in self.items()
+ if pattern_re.search(key))
+
+ def copy(self):
+ """Copy this RcParams instance."""
+ rccopy = RcParams()
+ for k in self: # Skip deprecations and revalidation.
+ rccopy._set(k, self._get(k))
+ return rccopy
+
+
+def rc_params(fail_on_error=False):
+ """Construct a `RcParams` instance from the default Matplotlib rc file."""
+ return rc_params_from_file(matplotlib_fname(), fail_on_error)
+
+
+@functools.cache
+def _get_ssl_context():
+ try:
+ import certifi
+ except ImportError:
+ _log.debug("Could not import certifi.")
+ return None
+ import ssl
+ return ssl.create_default_context(cafile=certifi.where())
+
+
+@contextlib.contextmanager
+def _open_file_or_url(fname):
+ if (isinstance(fname, str)
+ and fname.startswith(('http://', 'https://', 'ftp://', 'file:'))):
+ import urllib.request
+ ssl_ctx = _get_ssl_context()
+ if ssl_ctx is None:
+ _log.debug(
+ "Could not get certifi ssl context, https may not work."
+ )
+ with urllib.request.urlopen(fname, context=ssl_ctx) as f:
+ yield (line.decode('utf-8') for line in f)
+ else:
+ fname = os.path.expanduser(fname)
+ with open(fname, encoding='utf-8') as f:
+ yield f
+
+
+def _rc_params_in_file(fname, transform=lambda x: x, fail_on_error=False):
+ """
+ Construct a `RcParams` instance from file *fname*.
+
+ Unlike `rc_params_from_file`, the configuration class only contains the
+ parameters specified in the file (i.e. default values are not filled in).
+
+ Parameters
+ ----------
+ fname : path-like
+ The loaded file.
+ transform : callable, default: the identity function
+ A function called on each individual line of the file to transform it,
+ before further parsing.
+ fail_on_error : bool, default: False
+ Whether invalid entries should result in an exception or a warning.
+ """
+ import matplotlib as mpl
+ rc_temp = {}
+ with _open_file_or_url(fname) as fd:
+ try:
+ for line_no, line in enumerate(fd, 1):
+ line = transform(line)
+ strippedline = cbook._strip_comment(line)
+ if not strippedline:
+ continue
+ tup = strippedline.split(':', 1)
+ if len(tup) != 2:
+ _log.warning('Missing colon in file %r, line %d (%r)',
+ fname, line_no, line.rstrip('\n'))
+ continue
+ key, val = tup
+ key = key.strip()
+ val = val.strip()
+ if val.startswith('"') and val.endswith('"'):
+ val = val[1:-1] # strip double quotes
+ if key in rc_temp:
+ _log.warning('Duplicate key in file %r, line %d (%r)',
+ fname, line_no, line.rstrip('\n'))
+ rc_temp[key] = (val, line, line_no)
+ except UnicodeDecodeError:
+ _log.warning('Cannot decode configuration file %r as utf-8.',
+ fname)
+ raise
+
+ config = RcParams()
+
+ for key, (val, line, line_no) in rc_temp.items():
+ if key in rcsetup._validators:
+ if fail_on_error:
+ config[key] = val # try to convert to proper type or raise
+ else:
+ try:
+ config[key] = val # try to convert to proper type or skip
+ except Exception as msg:
+ _log.warning('Bad value in file %r, line %d (%r): %s',
+ fname, line_no, line.rstrip('\n'), msg)
+ elif key in _deprecated_ignore_map:
+ version, alt_key = _deprecated_ignore_map[key]
+ _api.warn_deprecated(
+ version, name=key, alternative=alt_key, obj_type='rcparam',
+ addendum="Please update your matplotlibrc.")
+ else:
+ # __version__ must be looked up as an attribute to trigger the
+ # module-level __getattr__.
+ version = ('main' if '.post' in mpl.__version__
+ else f'v{mpl.__version__}')
+ _log.warning("""
+Bad key %(key)s in file %(fname)s, line %(line_no)s (%(line)r)
+You probably need to get an updated matplotlibrc file from
+https://github.com/matplotlib/matplotlib/blob/%(version)s/lib/matplotlib/mpl-data/matplotlibrc
+or from the matplotlib source distribution""",
+ dict(key=key, fname=fname, line_no=line_no,
+ line=line.rstrip('\n'), version=version))
+ return config
+
+
+def rc_params_from_file(fname, fail_on_error=False, use_default_template=True):
+ """
+ Construct a `RcParams` from file *fname*.
+
+ Parameters
+ ----------
+ fname : str or path-like
+ A file with Matplotlib rc settings.
+ fail_on_error : bool
+ If True, raise an error when the parser fails to convert a parameter.
+ use_default_template : bool
+ If True, initialize with default parameters before updating with those
+ in the given file. If False, the configuration class only contains the
+ parameters specified in the file. (Useful for updating dicts.)
+ """
+ config_from_file = _rc_params_in_file(fname, fail_on_error=fail_on_error)
+
+ if not use_default_template:
+ return config_from_file
+
+ with _api.suppress_matplotlib_deprecation_warning():
+ config = RcParams({**rcParamsDefault, **config_from_file})
+
+ if "".join(config['text.latex.preamble']):
+ _log.info("""
+*****************************************************************
+You have the following UNSUPPORTED LaTeX preamble customizations:
+%s
+Please do not ask for support with these customizations active.
+*****************************************************************
+""", '\n'.join(config['text.latex.preamble']))
+ _log.debug('loaded rc file %s', fname)
+
+ return config
+
+
+rcParamsDefault = _rc_params_in_file(
+ cbook._get_data_path("matplotlibrc"),
+ # Strip leading comment.
+ transform=lambda line: line[1:] if line.startswith("#") else line,
+ fail_on_error=True)
+rcParamsDefault._update_raw(rcsetup._hardcoded_defaults)
+rcParamsDefault._ensure_has_backend()
+
+rcParams = RcParams() # The global instance.
+rcParams._update_raw(rcParamsDefault)
+rcParams._update_raw(_rc_params_in_file(matplotlib_fname()))
+rcParamsOrig = rcParams.copy()
+with _api.suppress_matplotlib_deprecation_warning():
+ # This also checks that all rcParams are indeed listed in the template.
+ # Assigning to rcsetup.defaultParams is left only for backcompat.
+ defaultParams = rcsetup.defaultParams = {
+ # We want to resolve deprecated rcParams, but not backend...
+ key: [(rcsetup._auto_backend_sentinel if key == "backend" else
+ rcParamsDefault[key]),
+ validator]
+ for key, validator in rcsetup._validators.items()}
+if rcParams['axes.formatter.use_locale']:
+ locale.setlocale(locale.LC_ALL, '')
+
+
+def rc(group, **kwargs):
+ """
+ Set the current `.rcParams`. *group* is the grouping for the rc, e.g.,
+ for ``lines.linewidth`` the group is ``lines``, for
+ ``axes.facecolor``, the group is ``axes``, and so on. Group may
+ also be a list or tuple of group names, e.g., (*xtick*, *ytick*).
+ *kwargs* is a dictionary attribute name/value pairs, e.g.,::
+
+ rc('lines', linewidth=2, color='r')
+
+ sets the current `.rcParams` and is equivalent to::
+
+ rcParams['lines.linewidth'] = 2
+ rcParams['lines.color'] = 'r'
+
+ The following aliases are available to save typing for interactive users:
+
+ ===== =================
+ Alias Property
+ ===== =================
+ 'lw' 'linewidth'
+ 'ls' 'linestyle'
+ 'c' 'color'
+ 'fc' 'facecolor'
+ 'ec' 'edgecolor'
+ 'mew' 'markeredgewidth'
+ 'aa' 'antialiased'
+ ===== =================
+
+ Thus you could abbreviate the above call as::
+
+ rc('lines', lw=2, c='r')
+
+ Note you can use python's kwargs dictionary facility to store
+ dictionaries of default parameters. e.g., you can customize the
+ font rc as follows::
+
+ font = {'family' : 'monospace',
+ 'weight' : 'bold',
+ 'size' : 'larger'}
+ rc('font', **font) # pass in the font dict as kwargs
+
+ This enables you to easily switch between several configurations. Use
+ ``matplotlib.style.use('default')`` or :func:`~matplotlib.rcdefaults` to
+ restore the default `.rcParams` after changes.
+
+ Notes
+ -----
+ Similar functionality is available by using the normal dict interface, i.e.
+ ``rcParams.update({"lines.linewidth": 2, ...})`` (but ``rcParams.update``
+ does not support abbreviations or grouping).
+ """
+
+ aliases = {
+ 'lw': 'linewidth',
+ 'ls': 'linestyle',
+ 'c': 'color',
+ 'fc': 'facecolor',
+ 'ec': 'edgecolor',
+ 'mew': 'markeredgewidth',
+ 'aa': 'antialiased',
+ }
+
+ if isinstance(group, str):
+ group = (group,)
+ for g in group:
+ for k, v in kwargs.items():
+ name = aliases.get(k) or k
+ key = f'{g}.{name}'
+ try:
+ rcParams[key] = v
+ except KeyError as err:
+ raise KeyError(('Unrecognized key "%s" for group "%s" and '
+ 'name "%s"') % (key, g, name)) from err
+
+
+def rcdefaults():
+ """
+ Restore the `.rcParams` from Matplotlib's internal default style.
+
+ Style-blacklisted `.rcParams` (defined in
+ ``matplotlib.style.core.STYLE_BLACKLIST``) are not updated.
+
+ See Also
+ --------
+ matplotlib.rc_file_defaults
+ Restore the `.rcParams` from the rc file originally loaded by
+ Matplotlib.
+ matplotlib.style.use
+ Use a specific style file. Call ``style.use('default')`` to restore
+ the default style.
+ """
+ # Deprecation warnings were already handled when creating rcParamsDefault,
+ # no need to reemit them here.
+ with _api.suppress_matplotlib_deprecation_warning():
+ from .style.core import STYLE_BLACKLIST
+ rcParams.clear()
+ rcParams.update({k: v for k, v in rcParamsDefault.items()
+ if k not in STYLE_BLACKLIST})
+
+
+def rc_file_defaults():
+ """
+ Restore the `.rcParams` from the original rc file loaded by Matplotlib.
+
+ Style-blacklisted `.rcParams` (defined in
+ ``matplotlib.style.core.STYLE_BLACKLIST``) are not updated.
+ """
+ # Deprecation warnings were already handled when creating rcParamsOrig, no
+ # need to reemit them here.
+ with _api.suppress_matplotlib_deprecation_warning():
+ from .style.core import STYLE_BLACKLIST
+ rcParams.update({k: rcParamsOrig[k] for k in rcParamsOrig
+ if k not in STYLE_BLACKLIST})
+
+
+def rc_file(fname, *, use_default_template=True):
+ """
+ Update `.rcParams` from file.
+
+ Style-blacklisted `.rcParams` (defined in
+ ``matplotlib.style.core.STYLE_BLACKLIST``) are not updated.
+
+ Parameters
+ ----------
+ fname : str or path-like
+ A file with Matplotlib rc settings.
+
+ use_default_template : bool
+ If True, initialize with default parameters before updating with those
+ in the given file. If False, the current configuration persists
+ and only the parameters specified in the file are updated.
+ """
+ # Deprecation warnings were already handled in rc_params_from_file, no need
+ # to reemit them here.
+ with _api.suppress_matplotlib_deprecation_warning():
+ from .style.core import STYLE_BLACKLIST
+ rc_from_file = rc_params_from_file(
+ fname, use_default_template=use_default_template)
+ rcParams.update({k: rc_from_file[k] for k in rc_from_file
+ if k not in STYLE_BLACKLIST})
+
+
+@contextlib.contextmanager
+def rc_context(rc=None, fname=None):
+ """
+ Return a context manager for temporarily changing rcParams.
+
+ The :rc:`backend` will not be reset by the context manager.
+
+ rcParams changed both through the context manager invocation and
+ in the body of the context will be reset on context exit.
+
+ Parameters
+ ----------
+ rc : dict
+ The rcParams to temporarily set.
+ fname : str or path-like
+ A file with Matplotlib rc settings. If both *fname* and *rc* are given,
+ settings from *rc* take precedence.
+
+ See Also
+ --------
+ :ref:`customizing-with-matplotlibrc-files`
+
+ Examples
+ --------
+ Passing explicit values via a dict::
+
+ with mpl.rc_context({'interactive': False}):
+ fig, ax = plt.subplots()
+ ax.plot(range(3), range(3))
+ fig.savefig('example.png')
+ plt.close(fig)
+
+ Loading settings from a file::
+
+ with mpl.rc_context(fname='print.rc'):
+ plt.plot(x, y) # uses 'print.rc'
+
+ Setting in the context body::
+
+ with mpl.rc_context():
+ # will be reset
+ mpl.rcParams['lines.linewidth'] = 5
+ plt.plot(x, y)
+
+ """
+ orig = dict(rcParams.copy())
+ del orig['backend']
+ try:
+ if fname:
+ rc_file(fname)
+ if rc:
+ rcParams.update(rc)
+ yield
+ finally:
+ rcParams._update_raw(orig) # Revert to the original rcs.
+
+
+def use(backend, *, force=True):
+ """
+ Select the backend used for rendering and GUI integration.
+
+ If pyplot is already imported, `~matplotlib.pyplot.switch_backend` is used
+ and if the new backend is different than the current backend, all Figures
+ will be closed.
+
+ Parameters
+ ----------
+ backend : str
+ The backend to switch to. This can either be one of the standard
+ backend names, which are case-insensitive:
+
+ - interactive backends:
+ GTK3Agg, GTK3Cairo, GTK4Agg, GTK4Cairo, MacOSX, nbAgg, notebook, QtAgg,
+ QtCairo, TkAgg, TkCairo, WebAgg, WX, WXAgg, WXCairo, Qt5Agg, Qt5Cairo
+
+ - non-interactive backends:
+ agg, cairo, pdf, pgf, ps, svg, template
+
+ or a string of the form: ``module://my.module.name``.
+
+ notebook is a synonym for nbAgg.
+
+ Switching to an interactive backend is not possible if an unrelated
+ event loop has already been started (e.g., switching to GTK3Agg if a
+ TkAgg window has already been opened). Switching to a non-interactive
+ backend is always possible.
+
+ force : bool, default: True
+ If True (the default), raise an `ImportError` if the backend cannot be
+ set up (either because it fails to import, or because an incompatible
+ GUI interactive framework is already running); if False, silently
+ ignore the failure.
+
+ See Also
+ --------
+ :ref:`backends`
+ matplotlib.get_backend
+ matplotlib.pyplot.switch_backend
+
+ """
+ name = rcsetup.validate_backend(backend)
+ # don't (prematurely) resolve the "auto" backend setting
+ if rcParams._get_backend_or_none() == name:
+ # Nothing to do if the requested backend is already set
+ pass
+ else:
+ # if pyplot is not already imported, do not import it. Doing
+ # so may trigger a `plt.switch_backend` to the _default_ backend
+ # before we get a chance to change to the one the user just requested
+ plt = sys.modules.get('matplotlib.pyplot')
+ # if pyplot is imported, then try to change backends
+ if plt is not None:
+ try:
+ # we need this import check here to re-raise if the
+ # user does not have the libraries to support their
+ # chosen backend installed.
+ plt.switch_backend(name)
+ except ImportError:
+ if force:
+ raise
+ # if we have not imported pyplot, then we can set the rcParam
+ # value which will be respected when the user finally imports
+ # pyplot
+ else:
+ rcParams['backend'] = backend
+ # if the user has asked for a given backend, do not helpfully
+ # fallback
+ rcParams['backend_fallback'] = False
+
+
+if os.environ.get('MPLBACKEND'):
+ rcParams['backend'] = os.environ.get('MPLBACKEND')
+
+
+def get_backend(*, auto_select=True):
+ """
+ Return the name of the current backend.
+
+ Parameters
+ ----------
+ auto_select : bool, default: True
+ Whether to trigger backend resolution if no backend has been
+ selected so far. If True, this ensures that a valid backend
+ is returned. If False, this returns None if no backend has been
+ selected so far.
+
+ .. versionadded:: 3.10
+
+ .. admonition:: Provisional
+
+ The *auto_select* flag is provisional. It may be changed or removed
+ without prior warning.
+
+ See Also
+ --------
+ matplotlib.use
+ """
+ if auto_select:
+ return rcParams['backend']
+ else:
+ backend = rcParams._get('backend')
+ if backend is rcsetup._auto_backend_sentinel:
+ return None
+ else:
+ return backend
+
+
+def interactive(b):
+ """
+ Set whether to redraw after every plotting command (e.g. `.pyplot.xlabel`).
+ """
+ rcParams['interactive'] = b
+
+
+def is_interactive():
+ """
+ Return whether to redraw after every plotting command.
+
+ .. note::
+
+ This function is only intended for use in backends. End users should
+ use `.pyplot.isinteractive` instead.
+ """
+ return rcParams['interactive']
+
+
+def _val_or_rc(val, rc_name):
+ """
+ If *val* is None, return ``mpl.rcParams[rc_name]``, otherwise return val.
+ """
+ return val if val is not None else rcParams[rc_name]
+
+
+def _init_tests():
+ # The version of FreeType to install locally for running the tests. This must match
+ # the value in `meson.build`.
+ LOCAL_FREETYPE_VERSION = '2.6.1'
+
+ from matplotlib import ft2font
+ if (ft2font.__freetype_version__ != LOCAL_FREETYPE_VERSION or
+ ft2font.__freetype_build_type__ != 'local'):
+ _log.warning(
+ "Matplotlib is not built with the correct FreeType version to run tests. "
+ "Rebuild without setting system-freetype=true in Meson setup options. "
+ "Expect many image comparison failures below. "
+ "Expected freetype version %s. "
+ "Found freetype version %s. "
+ "Freetype build type is %slocal.",
+ LOCAL_FREETYPE_VERSION,
+ ft2font.__freetype_version__,
+ "" if ft2font.__freetype_build_type__ == 'local' else "not ")
+
+
+def _replacer(data, value):
+ """
+ Either returns ``data[value]`` or passes ``data`` back, converts either to
+ a sequence.
+ """
+ try:
+ # if key isn't a string don't bother
+ if isinstance(value, str):
+ # try to use __getitem__
+ value = data[value]
+ except Exception:
+ # key does not exist, silently fall back to key
+ pass
+ return cbook.sanitize_sequence(value)
+
+
+def _label_from_arg(y, default_name):
+ try:
+ return y.name
+ except AttributeError:
+ if isinstance(default_name, str):
+ return default_name
+ return None
+
+
+def _add_data_doc(docstring, replace_names):
+ """
+ Add documentation for a *data* field to the given docstring.
+
+ Parameters
+ ----------
+ docstring : str
+ The input docstring.
+ replace_names : list of str or None
+ The list of parameter names which arguments should be replaced by
+ ``data[name]`` (if ``data[name]`` does not throw an exception). If
+ None, replacement is attempted for all arguments.
+
+ Returns
+ -------
+ str
+ The augmented docstring.
+ """
+ if (docstring is None
+ or replace_names is not None and len(replace_names) == 0):
+ return docstring
+ docstring = inspect.cleandoc(docstring)
+
+ data_doc = ("""\
+ If given, all parameters also accept a string ``s``, which is
+ interpreted as ``data[s]`` if ``s`` is a key in ``data``."""
+ if replace_names is None else f"""\
+ If given, the following parameters also accept a string ``s``, which is
+ interpreted as ``data[s]`` if ``s`` is a key in ``data``:
+
+ {', '.join(map('*{}*'.format, replace_names))}""")
+ # using string replacement instead of formatting has the advantages
+ # 1) simpler indent handling
+ # 2) prevent problems with formatting characters '{', '%' in the docstring
+ if _log.level <= logging.DEBUG:
+ # test_data_parameter_replacement() tests against these log messages
+ # make sure to keep message and test in sync
+ if "data : indexable object, optional" not in docstring:
+ _log.debug("data parameter docstring error: no data parameter")
+ if 'DATA_PARAMETER_PLACEHOLDER' not in docstring:
+ _log.debug("data parameter docstring error: missing placeholder")
+ return docstring.replace(' DATA_PARAMETER_PLACEHOLDER', data_doc)
+
+
+def _preprocess_data(func=None, *, replace_names=None, label_namer=None):
+ """
+ A decorator to add a 'data' kwarg to a function.
+
+ When applied::
+
+ @_preprocess_data()
+ def func(ax, *args, **kwargs): ...
+
+ the signature is modified to ``decorated(ax, *args, data=None, **kwargs)``
+ with the following behavior:
+
+ - if called with ``data=None``, forward the other arguments to ``func``;
+ - otherwise, *data* must be a mapping; for any argument passed in as a
+ string ``name``, replace the argument by ``data[name]`` (if this does not
+ throw an exception), then forward the arguments to ``func``.
+
+ In either case, any argument that is a `MappingView` is also converted to a
+ list.
+
+ Parameters
+ ----------
+ replace_names : list of str or None, default: None
+ The list of parameter names for which lookup into *data* should be
+ attempted. If None, replacement is attempted for all arguments.
+ label_namer : str, default: None
+ If set e.g. to "namer" (which must be a kwarg in the function's
+ signature -- not as ``**kwargs``), if the *namer* argument passed in is
+ a (string) key of *data* and no *label* kwarg is passed, then use the
+ (string) value of the *namer* as *label*. ::
+
+ @_preprocess_data(label_namer="foo")
+ def func(foo, label=None): ...
+
+ func("key", data={"key": value})
+ # is equivalent to
+ func.__wrapped__(value, label="key")
+ """
+
+ if func is None: # Return the actual decorator.
+ return functools.partial(
+ _preprocess_data,
+ replace_names=replace_names, label_namer=label_namer)
+
+ sig = inspect.signature(func)
+ varargs_name = None
+ varkwargs_name = None
+ arg_names = []
+ params = list(sig.parameters.values())
+ for p in params:
+ if p.kind is Parameter.VAR_POSITIONAL:
+ varargs_name = p.name
+ elif p.kind is Parameter.VAR_KEYWORD:
+ varkwargs_name = p.name
+ else:
+ arg_names.append(p.name)
+ data_param = Parameter("data", Parameter.KEYWORD_ONLY, default=None)
+ if varkwargs_name:
+ params.insert(-1, data_param)
+ else:
+ params.append(data_param)
+ new_sig = sig.replace(parameters=params)
+ arg_names = arg_names[1:] # remove the first "ax" / self arg
+
+ assert {*arg_names}.issuperset(replace_names or []) or varkwargs_name, (
+ "Matplotlib internal error: invalid replace_names "
+ f"({replace_names!r}) for {func.__name__!r}")
+ assert label_namer is None or label_namer in arg_names, (
+ "Matplotlib internal error: invalid label_namer "
+ f"({label_namer!r}) for {func.__name__!r}")
+
+ @functools.wraps(func)
+ def inner(ax, *args, data=None, **kwargs):
+ if data is None:
+ return func(
+ ax,
+ *map(cbook.sanitize_sequence, args),
+ **{k: cbook.sanitize_sequence(v) for k, v in kwargs.items()})
+
+ bound = new_sig.bind(ax, *args, **kwargs)
+ auto_label = (bound.arguments.get(label_namer)
+ or bound.kwargs.get(label_namer))
+
+ for k, v in bound.arguments.items():
+ if k == varkwargs_name:
+ for k1, v1 in v.items():
+ if replace_names is None or k1 in replace_names:
+ v[k1] = _replacer(data, v1)
+ elif k == varargs_name:
+ if replace_names is None:
+ bound.arguments[k] = tuple(_replacer(data, v1) for v1 in v)
+ else:
+ if replace_names is None or k in replace_names:
+ bound.arguments[k] = _replacer(data, v)
+
+ new_args = bound.args
+ new_kwargs = bound.kwargs
+
+ args_and_kwargs = {**bound.arguments, **bound.kwargs}
+ if label_namer and "label" not in args_and_kwargs:
+ new_kwargs["label"] = _label_from_arg(
+ args_and_kwargs.get(label_namer), auto_label)
+
+ return func(*new_args, **new_kwargs)
+
+ inner.__doc__ = _add_data_doc(inner.__doc__, replace_names)
+ inner.__signature__ = new_sig
+ return inner
+
+
+_log.debug('interactive is %s', is_interactive())
+_log.debug('platform is %s', sys.platform)
+
+
+@_api.deprecated("3.10", alternative="matplotlib.cbook.sanitize_sequence")
+def sanitize_sequence(data):
+ return cbook.sanitize_sequence(data)
+
+
+@_api.deprecated("3.10", alternative="matplotlib.rcsetup.validate_backend")
+def validate_backend(s):
+ return rcsetup.validate_backend(s)
+
+
+# workaround: we must defer colormaps import to after loading rcParams, because
+# colormap creation depends on rcParams
+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/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/__init__.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/__init__.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..88058ffd7def28740b4942d3851a5f43e49b086a
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/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/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_afm.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_afm.py
new file mode 100644
index 0000000000000000000000000000000000000000..558efe16392f7d386f642c86a8b028d10a778f25
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/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/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_animation_data.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_animation_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..8cbd312d8f142d8b4ec3a3ad3e005a14f380ec13
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_animation_data.py
@@ -0,0 +1,262 @@
+# JavaScript template for HTMLWriter
+JS_INCLUDE = """
+
+
+"""
+
+
+# Style definitions for the HTML template
+STYLE_INCLUDE = """
+
+"""
+
+
+# HTML template for HTMLWriter
+DISPLAY_TEMPLATE = """
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+""" # noqa: E501
+
+
+INCLUDED_FRAMES = """
+ for (var i=0; i<{Nframes}; i++){{
+ frames[i] = "{frame_dir}/frame" + ("0000000" + i).slice(-7) +
+ ".{frame_format}";
+ }}
+"""
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_blocking_input.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_blocking_input.py
new file mode 100644
index 0000000000000000000000000000000000000000..45f0775714431e73c283fede1f0cf12d7eaabb8d
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_blocking_input.py
@@ -0,0 +1,30 @@
+def blocking_input_loop(figure, event_names, timeout, handler):
+ """
+ Run *figure*'s event loop while listening to interactive events.
+
+ The events listed in *event_names* are passed to *handler*.
+
+ This function is used to implement `.Figure.waitforbuttonpress`,
+ `.Figure.ginput`, and `.Axes.clabel`.
+
+ Parameters
+ ----------
+ figure : `~matplotlib.figure.Figure`
+ event_names : list of str
+ The names of the events passed to *handler*.
+ timeout : float
+ If positive, the event loop is stopped after *timeout* seconds.
+ handler : Callable[[Event], Any]
+ Function called for each event; it can force an early exit of the event
+ loop by calling ``canvas.stop_event_loop()``.
+ """
+ if figure.canvas.manager:
+ figure.show() # Ensure that the figure is shown if we are managing it.
+ # Connect the events to the on_event function call.
+ cids = [figure.canvas.mpl_connect(name, handler) for name in event_names]
+ try:
+ figure.canvas.start_event_loop(timeout) # Start event loop.
+ finally: # Run even on exception like ctrl-c.
+ # Disconnect the callbacks.
+ for cid in cids:
+ figure.canvas.mpl_disconnect(cid)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_c_internal_utils.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_c_internal_utils.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..ccc172cde27a35ad930cc618b86fdf5c8d44728e
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_c_internal_utils.pyi
@@ -0,0 +1,8 @@
+def display_is_valid() -> bool: ...
+def xdisplay_is_valid() -> bool: ...
+
+def Win32_GetForegroundWindow() -> int | None: ...
+def Win32_SetForegroundWindow(hwnd: int) -> None: ...
+def Win32_SetProcessDpiAwareness_max() -> None: ...
+def Win32_SetCurrentProcessExplicitAppUserModelID(appid: str) -> None: ...
+def Win32_GetCurrentProcessExplicitAppUserModelID() -> str | None: ...
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_cm.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_cm.py
new file mode 100644
index 0000000000000000000000000000000000000000..b942d1697934789f26c522b3e7592671540919a6
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_cm.py
@@ -0,0 +1,1460 @@
+"""
+Nothing here but dictionaries for generating LinearSegmentedColormaps,
+and a dictionary of these dictionaries.
+
+Documentation for each is in pyplot.colormaps(). Please update this
+with the purpose and type of your colormap if you add data for one here.
+"""
+
+from functools import partial
+
+import numpy as np
+
+_binary_data = {
+ 'red': ((0., 1., 1.), (1., 0., 0.)),
+ 'green': ((0., 1., 1.), (1., 0., 0.)),
+ 'blue': ((0., 1., 1.), (1., 0., 0.))
+ }
+
+_autumn_data = {'red': ((0., 1.0, 1.0), (1.0, 1.0, 1.0)),
+ 'green': ((0., 0., 0.), (1.0, 1.0, 1.0)),
+ 'blue': ((0., 0., 0.), (1.0, 0., 0.))}
+
+_bone_data = {'red': ((0., 0., 0.),
+ (0.746032, 0.652778, 0.652778),
+ (1.0, 1.0, 1.0)),
+ 'green': ((0., 0., 0.),
+ (0.365079, 0.319444, 0.319444),
+ (0.746032, 0.777778, 0.777778),
+ (1.0, 1.0, 1.0)),
+ 'blue': ((0., 0., 0.),
+ (0.365079, 0.444444, 0.444444),
+ (1.0, 1.0, 1.0))}
+
+_cool_data = {'red': ((0., 0., 0.), (1.0, 1.0, 1.0)),
+ 'green': ((0., 1., 1.), (1.0, 0., 0.)),
+ 'blue': ((0., 1., 1.), (1.0, 1., 1.))}
+
+_copper_data = {'red': ((0., 0., 0.),
+ (0.809524, 1.000000, 1.000000),
+ (1.0, 1.0, 1.0)),
+ 'green': ((0., 0., 0.),
+ (1.0, 0.7812, 0.7812)),
+ 'blue': ((0., 0., 0.),
+ (1.0, 0.4975, 0.4975))}
+
+def _flag_red(x): return 0.75 * np.sin((x * 31.5 + 0.25) * np.pi) + 0.5
+def _flag_green(x): return np.sin(x * 31.5 * np.pi)
+def _flag_blue(x): return 0.75 * np.sin((x * 31.5 - 0.25) * np.pi) + 0.5
+_flag_data = {'red': _flag_red, 'green': _flag_green, 'blue': _flag_blue}
+
+def _prism_red(x): return 0.75 * np.sin((x * 20.9 + 0.25) * np.pi) + 0.67
+def _prism_green(x): return 0.75 * np.sin((x * 20.9 - 0.25) * np.pi) + 0.33
+def _prism_blue(x): return -1.1 * np.sin((x * 20.9) * np.pi)
+_prism_data = {'red': _prism_red, 'green': _prism_green, 'blue': _prism_blue}
+
+def _ch_helper(gamma, s, r, h, p0, p1, x):
+ """Helper function for generating picklable cubehelix colormaps."""
+ # Apply gamma factor to emphasise low or high intensity values
+ xg = x ** gamma
+ # Calculate amplitude and angle of deviation from the black to white
+ # diagonal in the plane of constant perceived intensity.
+ a = h * xg * (1 - xg) / 2
+ phi = 2 * np.pi * (s / 3 + r * x)
+ return xg + a * (p0 * np.cos(phi) + p1 * np.sin(phi))
+
+def cubehelix(gamma=1.0, s=0.5, r=-1.5, h=1.0):
+ """
+ Return custom data dictionary of (r, g, b) conversion functions, which can
+ be used with `.ColormapRegistry.register`, for the cubehelix color scheme.
+
+ Unlike most other color schemes cubehelix was designed by D.A. Green to
+ be monotonically increasing in terms of perceived brightness.
+ Also, when printed on a black and white postscript printer, the scheme
+ results in a greyscale with monotonically increasing brightness.
+ This color scheme is named cubehelix because the (r, g, b) values produced
+ can be visualised as a squashed helix around the diagonal in the
+ (r, g, b) color cube.
+
+ For a unit color cube (i.e. 3D coordinates for (r, g, b) each in the
+ range 0 to 1) the color scheme starts at (r, g, b) = (0, 0, 0), i.e. black,
+ and finishes at (r, g, b) = (1, 1, 1), i.e. white. For some fraction *x*,
+ between 0 and 1, the color is the corresponding grey value at that
+ fraction along the black to white diagonal (x, x, x) plus a color
+ element. This color element is calculated in a plane of constant
+ perceived intensity and controlled by the following parameters.
+
+ Parameters
+ ----------
+ gamma : float, default: 1
+ Gamma factor emphasizing either low intensity values (gamma < 1), or
+ high intensity values (gamma > 1).
+ s : float, default: 0.5 (purple)
+ The starting color.
+ r : float, default: -1.5
+ The number of r, g, b rotations in color that are made from the start
+ to the end of the color scheme. The default of -1.5 corresponds to ->
+ B -> G -> R -> B.
+ h : float, default: 1
+ The hue, i.e. how saturated the colors are. If this parameter is zero
+ then the color scheme is purely a greyscale.
+ """
+ return {'red': partial(_ch_helper, gamma, s, r, h, -0.14861, 1.78277),
+ 'green': partial(_ch_helper, gamma, s, r, h, -0.29227, -0.90649),
+ 'blue': partial(_ch_helper, gamma, s, r, h, 1.97294, 0.0)}
+
+_cubehelix_data = cubehelix()
+
+_bwr_data = ((0.0, 0.0, 1.0), (1.0, 1.0, 1.0), (1.0, 0.0, 0.0))
+_brg_data = ((0.0, 0.0, 1.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0))
+
+# Gnuplot palette functions
+def _g0(x): return 0
+def _g1(x): return 0.5
+def _g2(x): return 1
+def _g3(x): return x
+def _g4(x): return x ** 2
+def _g5(x): return x ** 3
+def _g6(x): return x ** 4
+def _g7(x): return np.sqrt(x)
+def _g8(x): return np.sqrt(np.sqrt(x))
+def _g9(x): return np.sin(x * np.pi / 2)
+def _g10(x): return np.cos(x * np.pi / 2)
+def _g11(x): return np.abs(x - 0.5)
+def _g12(x): return (2 * x - 1) ** 2
+def _g13(x): return np.sin(x * np.pi)
+def _g14(x): return np.abs(np.cos(x * np.pi))
+def _g15(x): return np.sin(x * 2 * np.pi)
+def _g16(x): return np.cos(x * 2 * np.pi)
+def _g17(x): return np.abs(np.sin(x * 2 * np.pi))
+def _g18(x): return np.abs(np.cos(x * 2 * np.pi))
+def _g19(x): return np.abs(np.sin(x * 4 * np.pi))
+def _g20(x): return np.abs(np.cos(x * 4 * np.pi))
+def _g21(x): return 3 * x
+def _g22(x): return 3 * x - 1
+def _g23(x): return 3 * x - 2
+def _g24(x): return np.abs(3 * x - 1)
+def _g25(x): return np.abs(3 * x - 2)
+def _g26(x): return (3 * x - 1) / 2
+def _g27(x): return (3 * x - 2) / 2
+def _g28(x): return np.abs((3 * x - 1) / 2)
+def _g29(x): return np.abs((3 * x - 2) / 2)
+def _g30(x): return x / 0.32 - 0.78125
+def _g31(x): return 2 * x - 0.84
+def _g32(x):
+ ret = np.zeros(len(x))
+ m = (x < 0.25)
+ ret[m] = 4 * x[m]
+ m = (x >= 0.25) & (x < 0.92)
+ ret[m] = -2 * x[m] + 1.84
+ m = (x >= 0.92)
+ ret[m] = x[m] / 0.08 - 11.5
+ return ret
+def _g33(x): return np.abs(2 * x - 0.5)
+def _g34(x): return 2 * x
+def _g35(x): return 2 * x - 0.5
+def _g36(x): return 2 * x - 1
+
+gfunc = {i: globals()[f"_g{i}"] for i in range(37)}
+
+_gnuplot_data = {
+ 'red': gfunc[7],
+ 'green': gfunc[5],
+ 'blue': gfunc[15],
+}
+
+_gnuplot2_data = {
+ 'red': gfunc[30],
+ 'green': gfunc[31],
+ 'blue': gfunc[32],
+}
+
+_ocean_data = {
+ 'red': gfunc[23],
+ 'green': gfunc[28],
+ 'blue': gfunc[3],
+}
+
+_afmhot_data = {
+ 'red': gfunc[34],
+ 'green': gfunc[35],
+ 'blue': gfunc[36],
+}
+
+_rainbow_data = {
+ 'red': gfunc[33],
+ 'green': gfunc[13],
+ 'blue': gfunc[10],
+}
+
+_seismic_data = (
+ (0.0, 0.0, 0.3), (0.0, 0.0, 1.0),
+ (1.0, 1.0, 1.0), (1.0, 0.0, 0.0),
+ (0.5, 0.0, 0.0))
+
+_terrain_data = (
+ (0.00, (0.2, 0.2, 0.6)),
+ (0.15, (0.0, 0.6, 1.0)),
+ (0.25, (0.0, 0.8, 0.4)),
+ (0.50, (1.0, 1.0, 0.6)),
+ (0.75, (0.5, 0.36, 0.33)),
+ (1.00, (1.0, 1.0, 1.0)))
+
+_gray_data = {'red': ((0., 0, 0), (1., 1, 1)),
+ 'green': ((0., 0, 0), (1., 1, 1)),
+ 'blue': ((0., 0, 0), (1., 1, 1))}
+
+_hot_data = {'red': ((0., 0.0416, 0.0416),
+ (0.365079, 1.000000, 1.000000),
+ (1.0, 1.0, 1.0)),
+ 'green': ((0., 0., 0.),
+ (0.365079, 0.000000, 0.000000),
+ (0.746032, 1.000000, 1.000000),
+ (1.0, 1.0, 1.0)),
+ 'blue': ((0., 0., 0.),
+ (0.746032, 0.000000, 0.000000),
+ (1.0, 1.0, 1.0))}
+
+_hsv_data = {'red': ((0., 1., 1.),
+ (0.158730, 1.000000, 1.000000),
+ (0.174603, 0.968750, 0.968750),
+ (0.333333, 0.031250, 0.031250),
+ (0.349206, 0.000000, 0.000000),
+ (0.666667, 0.000000, 0.000000),
+ (0.682540, 0.031250, 0.031250),
+ (0.841270, 0.968750, 0.968750),
+ (0.857143, 1.000000, 1.000000),
+ (1.0, 1.0, 1.0)),
+ 'green': ((0., 0., 0.),
+ (0.158730, 0.937500, 0.937500),
+ (0.174603, 1.000000, 1.000000),
+ (0.507937, 1.000000, 1.000000),
+ (0.666667, 0.062500, 0.062500),
+ (0.682540, 0.000000, 0.000000),
+ (1.0, 0., 0.)),
+ 'blue': ((0., 0., 0.),
+ (0.333333, 0.000000, 0.000000),
+ (0.349206, 0.062500, 0.062500),
+ (0.507937, 1.000000, 1.000000),
+ (0.841270, 1.000000, 1.000000),
+ (0.857143, 0.937500, 0.937500),
+ (1.0, 0.09375, 0.09375))}
+
+_jet_data = {'red': ((0.00, 0, 0),
+ (0.35, 0, 0),
+ (0.66, 1, 1),
+ (0.89, 1, 1),
+ (1.00, 0.5, 0.5)),
+ 'green': ((0.000, 0, 0),
+ (0.125, 0, 0),
+ (0.375, 1, 1),
+ (0.640, 1, 1),
+ (0.910, 0, 0),
+ (1.000, 0, 0)),
+ 'blue': ((0.00, 0.5, 0.5),
+ (0.11, 1, 1),
+ (0.34, 1, 1),
+ (0.65, 0, 0),
+ (1.00, 0, 0))}
+
+_pink_data = {'red': ((0., 0.1178, 0.1178), (0.015873, 0.195857, 0.195857),
+ (0.031746, 0.250661, 0.250661),
+ (0.047619, 0.295468, 0.295468),
+ (0.063492, 0.334324, 0.334324),
+ (0.079365, 0.369112, 0.369112),
+ (0.095238, 0.400892, 0.400892),
+ (0.111111, 0.430331, 0.430331),
+ (0.126984, 0.457882, 0.457882),
+ (0.142857, 0.483867, 0.483867),
+ (0.158730, 0.508525, 0.508525),
+ (0.174603, 0.532042, 0.532042),
+ (0.190476, 0.554563, 0.554563),
+ (0.206349, 0.576204, 0.576204),
+ (0.222222, 0.597061, 0.597061),
+ (0.238095, 0.617213, 0.617213),
+ (0.253968, 0.636729, 0.636729),
+ (0.269841, 0.655663, 0.655663),
+ (0.285714, 0.674066, 0.674066),
+ (0.301587, 0.691980, 0.691980),
+ (0.317460, 0.709441, 0.709441),
+ (0.333333, 0.726483, 0.726483),
+ (0.349206, 0.743134, 0.743134),
+ (0.365079, 0.759421, 0.759421),
+ (0.380952, 0.766356, 0.766356),
+ (0.396825, 0.773229, 0.773229),
+ (0.412698, 0.780042, 0.780042),
+ (0.428571, 0.786796, 0.786796),
+ (0.444444, 0.793492, 0.793492),
+ (0.460317, 0.800132, 0.800132),
+ (0.476190, 0.806718, 0.806718),
+ (0.492063, 0.813250, 0.813250),
+ (0.507937, 0.819730, 0.819730),
+ (0.523810, 0.826160, 0.826160),
+ (0.539683, 0.832539, 0.832539),
+ (0.555556, 0.838870, 0.838870),
+ (0.571429, 0.845154, 0.845154),
+ (0.587302, 0.851392, 0.851392),
+ (0.603175, 0.857584, 0.857584),
+ (0.619048, 0.863731, 0.863731),
+ (0.634921, 0.869835, 0.869835),
+ (0.650794, 0.875897, 0.875897),
+ (0.666667, 0.881917, 0.881917),
+ (0.682540, 0.887896, 0.887896),
+ (0.698413, 0.893835, 0.893835),
+ (0.714286, 0.899735, 0.899735),
+ (0.730159, 0.905597, 0.905597),
+ (0.746032, 0.911421, 0.911421),
+ (0.761905, 0.917208, 0.917208),
+ (0.777778, 0.922958, 0.922958),
+ (0.793651, 0.928673, 0.928673),
+ (0.809524, 0.934353, 0.934353),
+ (0.825397, 0.939999, 0.939999),
+ (0.841270, 0.945611, 0.945611),
+ (0.857143, 0.951190, 0.951190),
+ (0.873016, 0.956736, 0.956736),
+ (0.888889, 0.962250, 0.962250),
+ (0.904762, 0.967733, 0.967733),
+ (0.920635, 0.973185, 0.973185),
+ (0.936508, 0.978607, 0.978607),
+ (0.952381, 0.983999, 0.983999),
+ (0.968254, 0.989361, 0.989361),
+ (0.984127, 0.994695, 0.994695), (1.0, 1.0, 1.0)),
+ 'green': ((0., 0., 0.), (0.015873, 0.102869, 0.102869),
+ (0.031746, 0.145479, 0.145479),
+ (0.047619, 0.178174, 0.178174),
+ (0.063492, 0.205738, 0.205738),
+ (0.079365, 0.230022, 0.230022),
+ (0.095238, 0.251976, 0.251976),
+ (0.111111, 0.272166, 0.272166),
+ (0.126984, 0.290957, 0.290957),
+ (0.142857, 0.308607, 0.308607),
+ (0.158730, 0.325300, 0.325300),
+ (0.174603, 0.341178, 0.341178),
+ (0.190476, 0.356348, 0.356348),
+ (0.206349, 0.370899, 0.370899),
+ (0.222222, 0.384900, 0.384900),
+ (0.238095, 0.398410, 0.398410),
+ (0.253968, 0.411476, 0.411476),
+ (0.269841, 0.424139, 0.424139),
+ (0.285714, 0.436436, 0.436436),
+ (0.301587, 0.448395, 0.448395),
+ (0.317460, 0.460044, 0.460044),
+ (0.333333, 0.471405, 0.471405),
+ (0.349206, 0.482498, 0.482498),
+ (0.365079, 0.493342, 0.493342),
+ (0.380952, 0.517549, 0.517549),
+ (0.396825, 0.540674, 0.540674),
+ (0.412698, 0.562849, 0.562849),
+ (0.428571, 0.584183, 0.584183),
+ (0.444444, 0.604765, 0.604765),
+ (0.460317, 0.624669, 0.624669),
+ (0.476190, 0.643958, 0.643958),
+ (0.492063, 0.662687, 0.662687),
+ (0.507937, 0.680900, 0.680900),
+ (0.523810, 0.698638, 0.698638),
+ (0.539683, 0.715937, 0.715937),
+ (0.555556, 0.732828, 0.732828),
+ (0.571429, 0.749338, 0.749338),
+ (0.587302, 0.765493, 0.765493),
+ (0.603175, 0.781313, 0.781313),
+ (0.619048, 0.796819, 0.796819),
+ (0.634921, 0.812029, 0.812029),
+ (0.650794, 0.826960, 0.826960),
+ (0.666667, 0.841625, 0.841625),
+ (0.682540, 0.856040, 0.856040),
+ (0.698413, 0.870216, 0.870216),
+ (0.714286, 0.884164, 0.884164),
+ (0.730159, 0.897896, 0.897896),
+ (0.746032, 0.911421, 0.911421),
+ (0.761905, 0.917208, 0.917208),
+ (0.777778, 0.922958, 0.922958),
+ (0.793651, 0.928673, 0.928673),
+ (0.809524, 0.934353, 0.934353),
+ (0.825397, 0.939999, 0.939999),
+ (0.841270, 0.945611, 0.945611),
+ (0.857143, 0.951190, 0.951190),
+ (0.873016, 0.956736, 0.956736),
+ (0.888889, 0.962250, 0.962250),
+ (0.904762, 0.967733, 0.967733),
+ (0.920635, 0.973185, 0.973185),
+ (0.936508, 0.978607, 0.978607),
+ (0.952381, 0.983999, 0.983999),
+ (0.968254, 0.989361, 0.989361),
+ (0.984127, 0.994695, 0.994695), (1.0, 1.0, 1.0)),
+ 'blue': ((0., 0., 0.), (0.015873, 0.102869, 0.102869),
+ (0.031746, 0.145479, 0.145479),
+ (0.047619, 0.178174, 0.178174),
+ (0.063492, 0.205738, 0.205738),
+ (0.079365, 0.230022, 0.230022),
+ (0.095238, 0.251976, 0.251976),
+ (0.111111, 0.272166, 0.272166),
+ (0.126984, 0.290957, 0.290957),
+ (0.142857, 0.308607, 0.308607),
+ (0.158730, 0.325300, 0.325300),
+ (0.174603, 0.341178, 0.341178),
+ (0.190476, 0.356348, 0.356348),
+ (0.206349, 0.370899, 0.370899),
+ (0.222222, 0.384900, 0.384900),
+ (0.238095, 0.398410, 0.398410),
+ (0.253968, 0.411476, 0.411476),
+ (0.269841, 0.424139, 0.424139),
+ (0.285714, 0.436436, 0.436436),
+ (0.301587, 0.448395, 0.448395),
+ (0.317460, 0.460044, 0.460044),
+ (0.333333, 0.471405, 0.471405),
+ (0.349206, 0.482498, 0.482498),
+ (0.365079, 0.493342, 0.493342),
+ (0.380952, 0.503953, 0.503953),
+ (0.396825, 0.514344, 0.514344),
+ (0.412698, 0.524531, 0.524531),
+ (0.428571, 0.534522, 0.534522),
+ (0.444444, 0.544331, 0.544331),
+ (0.460317, 0.553966, 0.553966),
+ (0.476190, 0.563436, 0.563436),
+ (0.492063, 0.572750, 0.572750),
+ (0.507937, 0.581914, 0.581914),
+ (0.523810, 0.590937, 0.590937),
+ (0.539683, 0.599824, 0.599824),
+ (0.555556, 0.608581, 0.608581),
+ (0.571429, 0.617213, 0.617213),
+ (0.587302, 0.625727, 0.625727),
+ (0.603175, 0.634126, 0.634126),
+ (0.619048, 0.642416, 0.642416),
+ (0.634921, 0.650600, 0.650600),
+ (0.650794, 0.658682, 0.658682),
+ (0.666667, 0.666667, 0.666667),
+ (0.682540, 0.674556, 0.674556),
+ (0.698413, 0.682355, 0.682355),
+ (0.714286, 0.690066, 0.690066),
+ (0.730159, 0.697691, 0.697691),
+ (0.746032, 0.705234, 0.705234),
+ (0.761905, 0.727166, 0.727166),
+ (0.777778, 0.748455, 0.748455),
+ (0.793651, 0.769156, 0.769156),
+ (0.809524, 0.789314, 0.789314),
+ (0.825397, 0.808969, 0.808969),
+ (0.841270, 0.828159, 0.828159),
+ (0.857143, 0.846913, 0.846913),
+ (0.873016, 0.865261, 0.865261),
+ (0.888889, 0.883229, 0.883229),
+ (0.904762, 0.900837, 0.900837),
+ (0.920635, 0.918109, 0.918109),
+ (0.936508, 0.935061, 0.935061),
+ (0.952381, 0.951711, 0.951711),
+ (0.968254, 0.968075, 0.968075),
+ (0.984127, 0.984167, 0.984167), (1.0, 1.0, 1.0))}
+
+_spring_data = {'red': ((0., 1., 1.), (1.0, 1.0, 1.0)),
+ 'green': ((0., 0., 0.), (1.0, 1.0, 1.0)),
+ 'blue': ((0., 1., 1.), (1.0, 0.0, 0.0))}
+
+
+_summer_data = {'red': ((0., 0., 0.), (1.0, 1.0, 1.0)),
+ 'green': ((0., 0.5, 0.5), (1.0, 1.0, 1.0)),
+ 'blue': ((0., 0.4, 0.4), (1.0, 0.4, 0.4))}
+
+
+_winter_data = {'red': ((0., 0., 0.), (1.0, 0.0, 0.0)),
+ 'green': ((0., 0., 0.), (1.0, 1.0, 1.0)),
+ 'blue': ((0., 1., 1.), (1.0, 0.5, 0.5))}
+
+_nipy_spectral_data = {
+ 'red': [
+ (0.0, 0.0, 0.0), (0.05, 0.4667, 0.4667),
+ (0.10, 0.5333, 0.5333), (0.15, 0.0, 0.0),
+ (0.20, 0.0, 0.0), (0.25, 0.0, 0.0),
+ (0.30, 0.0, 0.0), (0.35, 0.0, 0.0),
+ (0.40, 0.0, 0.0), (0.45, 0.0, 0.0),
+ (0.50, 0.0, 0.0), (0.55, 0.0, 0.0),
+ (0.60, 0.0, 0.0), (0.65, 0.7333, 0.7333),
+ (0.70, 0.9333, 0.9333), (0.75, 1.0, 1.0),
+ (0.80, 1.0, 1.0), (0.85, 1.0, 1.0),
+ (0.90, 0.8667, 0.8667), (0.95, 0.80, 0.80),
+ (1.0, 0.80, 0.80),
+ ],
+ 'green': [
+ (0.0, 0.0, 0.0), (0.05, 0.0, 0.0),
+ (0.10, 0.0, 0.0), (0.15, 0.0, 0.0),
+ (0.20, 0.0, 0.0), (0.25, 0.4667, 0.4667),
+ (0.30, 0.6000, 0.6000), (0.35, 0.6667, 0.6667),
+ (0.40, 0.6667, 0.6667), (0.45, 0.6000, 0.6000),
+ (0.50, 0.7333, 0.7333), (0.55, 0.8667, 0.8667),
+ (0.60, 1.0, 1.0), (0.65, 1.0, 1.0),
+ (0.70, 0.9333, 0.9333), (0.75, 0.8000, 0.8000),
+ (0.80, 0.6000, 0.6000), (0.85, 0.0, 0.0),
+ (0.90, 0.0, 0.0), (0.95, 0.0, 0.0),
+ (1.0, 0.80, 0.80),
+ ],
+ 'blue': [
+ (0.0, 0.0, 0.0), (0.05, 0.5333, 0.5333),
+ (0.10, 0.6000, 0.6000), (0.15, 0.6667, 0.6667),
+ (0.20, 0.8667, 0.8667), (0.25, 0.8667, 0.8667),
+ (0.30, 0.8667, 0.8667), (0.35, 0.6667, 0.6667),
+ (0.40, 0.5333, 0.5333), (0.45, 0.0, 0.0),
+ (0.5, 0.0, 0.0), (0.55, 0.0, 0.0),
+ (0.60, 0.0, 0.0), (0.65, 0.0, 0.0),
+ (0.70, 0.0, 0.0), (0.75, 0.0, 0.0),
+ (0.80, 0.0, 0.0), (0.85, 0.0, 0.0),
+ (0.90, 0.0, 0.0), (0.95, 0.0, 0.0),
+ (1.0, 0.80, 0.80),
+ ],
+}
+
+
+# 34 colormaps based on color specifications and designs
+# developed by Cynthia Brewer (https://colorbrewer2.org/).
+# The ColorBrewer palettes have been included under the terms
+# of an Apache-stype license (for details, see the file
+# LICENSE_COLORBREWER in the license directory of the matplotlib
+# source distribution).
+
+# RGB values taken from Brewer's Excel sheet, divided by 255
+
+_Blues_data = (
+ (0.96862745098039216, 0.98431372549019602, 1.0 ),
+ (0.87058823529411766, 0.92156862745098034, 0.96862745098039216),
+ (0.77647058823529413, 0.85882352941176465, 0.93725490196078431),
+ (0.61960784313725492, 0.792156862745098 , 0.88235294117647056),
+ (0.41960784313725491, 0.68235294117647061, 0.83921568627450982),
+ (0.25882352941176473, 0.5725490196078431 , 0.77647058823529413),
+ (0.12941176470588237, 0.44313725490196076, 0.70980392156862748),
+ (0.03137254901960784, 0.31764705882352939, 0.61176470588235299),
+ (0.03137254901960784, 0.18823529411764706, 0.41960784313725491)
+ )
+
+_BrBG_data = (
+ (0.32941176470588235, 0.18823529411764706, 0.0196078431372549 ),
+ (0.5490196078431373 , 0.31764705882352939, 0.0392156862745098 ),
+ (0.74901960784313726, 0.50588235294117645, 0.17647058823529413),
+ (0.87450980392156863, 0.76078431372549016, 0.49019607843137253),
+ (0.96470588235294119, 0.90980392156862744, 0.76470588235294112),
+ (0.96078431372549022, 0.96078431372549022, 0.96078431372549022),
+ (0.7803921568627451 , 0.91764705882352937, 0.89803921568627454),
+ (0.50196078431372548, 0.80392156862745101, 0.75686274509803919),
+ (0.20784313725490197, 0.59215686274509804, 0.5607843137254902 ),
+ (0.00392156862745098, 0.4 , 0.36862745098039218),
+ (0.0 , 0.23529411764705882, 0.18823529411764706)
+ )
+
+_BuGn_data = (
+ (0.96862745098039216, 0.9882352941176471 , 0.99215686274509807),
+ (0.89803921568627454, 0.96078431372549022, 0.97647058823529409),
+ (0.8 , 0.92549019607843142, 0.90196078431372551),
+ (0.6 , 0.84705882352941175, 0.78823529411764703),
+ (0.4 , 0.76078431372549016, 0.64313725490196083),
+ (0.25490196078431371, 0.68235294117647061, 0.46274509803921571),
+ (0.13725490196078433, 0.54509803921568623, 0.27058823529411763),
+ (0.0 , 0.42745098039215684, 0.17254901960784313),
+ (0.0 , 0.26666666666666666, 0.10588235294117647)
+ )
+
+_BuPu_data = (
+ (0.96862745098039216, 0.9882352941176471 , 0.99215686274509807),
+ (0.8784313725490196 , 0.92549019607843142, 0.95686274509803926),
+ (0.74901960784313726, 0.82745098039215681, 0.90196078431372551),
+ (0.61960784313725492, 0.73725490196078436, 0.85490196078431369),
+ (0.5490196078431373 , 0.58823529411764708, 0.77647058823529413),
+ (0.5490196078431373 , 0.41960784313725491, 0.69411764705882351),
+ (0.53333333333333333, 0.25490196078431371, 0.61568627450980395),
+ (0.50588235294117645, 0.05882352941176471, 0.48627450980392156),
+ (0.30196078431372547, 0.0 , 0.29411764705882354)
+ )
+
+_GnBu_data = (
+ (0.96862745098039216, 0.9882352941176471 , 0.94117647058823528),
+ (0.8784313725490196 , 0.95294117647058818, 0.85882352941176465),
+ (0.8 , 0.92156862745098034, 0.77254901960784317),
+ (0.6588235294117647 , 0.8666666666666667 , 0.70980392156862748),
+ (0.4823529411764706 , 0.8 , 0.7686274509803922 ),
+ (0.30588235294117649, 0.70196078431372544, 0.82745098039215681),
+ (0.16862745098039217, 0.5490196078431373 , 0.74509803921568629),
+ (0.03137254901960784, 0.40784313725490196, 0.67450980392156867),
+ (0.03137254901960784, 0.25098039215686274, 0.50588235294117645)
+ )
+
+_Greens_data = (
+ (0.96862745098039216, 0.9882352941176471 , 0.96078431372549022),
+ (0.89803921568627454, 0.96078431372549022, 0.8784313725490196 ),
+ (0.7803921568627451 , 0.9137254901960784 , 0.75294117647058822),
+ (0.63137254901960782, 0.85098039215686272, 0.60784313725490191),
+ (0.45490196078431372, 0.7686274509803922 , 0.46274509803921571),
+ (0.25490196078431371, 0.6705882352941176 , 0.36470588235294116),
+ (0.13725490196078433, 0.54509803921568623, 0.27058823529411763),
+ (0.0 , 0.42745098039215684, 0.17254901960784313),
+ (0.0 , 0.26666666666666666, 0.10588235294117647)
+ )
+
+_Greys_data = (
+ (1.0 , 1.0 , 1.0 ),
+ (0.94117647058823528, 0.94117647058823528, 0.94117647058823528),
+ (0.85098039215686272, 0.85098039215686272, 0.85098039215686272),
+ (0.74117647058823533, 0.74117647058823533, 0.74117647058823533),
+ (0.58823529411764708, 0.58823529411764708, 0.58823529411764708),
+ (0.45098039215686275, 0.45098039215686275, 0.45098039215686275),
+ (0.32156862745098042, 0.32156862745098042, 0.32156862745098042),
+ (0.14509803921568629, 0.14509803921568629, 0.14509803921568629),
+ (0.0 , 0.0 , 0.0 )
+ )
+
+_Oranges_data = (
+ (1.0 , 0.96078431372549022, 0.92156862745098034),
+ (0.99607843137254903, 0.90196078431372551, 0.80784313725490198),
+ (0.99215686274509807, 0.81568627450980391, 0.63529411764705879),
+ (0.99215686274509807, 0.68235294117647061, 0.41960784313725491),
+ (0.99215686274509807, 0.55294117647058827, 0.23529411764705882),
+ (0.94509803921568625, 0.41176470588235292, 0.07450980392156863),
+ (0.85098039215686272, 0.28235294117647058, 0.00392156862745098),
+ (0.65098039215686276, 0.21176470588235294, 0.01176470588235294),
+ (0.49803921568627452, 0.15294117647058825, 0.01568627450980392)
+ )
+
+_OrRd_data = (
+ (1.0 , 0.96862745098039216, 0.92549019607843142),
+ (0.99607843137254903, 0.90980392156862744, 0.78431372549019607),
+ (0.99215686274509807, 0.83137254901960789, 0.61960784313725492),
+ (0.99215686274509807, 0.73333333333333328, 0.51764705882352946),
+ (0.9882352941176471 , 0.55294117647058827, 0.34901960784313724),
+ (0.93725490196078431, 0.396078431372549 , 0.28235294117647058),
+ (0.84313725490196079, 0.18823529411764706, 0.12156862745098039),
+ (0.70196078431372544, 0.0 , 0.0 ),
+ (0.49803921568627452, 0.0 , 0.0 )
+ )
+
+_PiYG_data = (
+ (0.55686274509803924, 0.00392156862745098, 0.32156862745098042),
+ (0.77254901960784317, 0.10588235294117647, 0.49019607843137253),
+ (0.87058823529411766, 0.46666666666666667, 0.68235294117647061),
+ (0.94509803921568625, 0.71372549019607845, 0.85490196078431369),
+ (0.99215686274509807, 0.8784313725490196 , 0.93725490196078431),
+ (0.96862745098039216, 0.96862745098039216, 0.96862745098039216),
+ (0.90196078431372551, 0.96078431372549022, 0.81568627450980391),
+ (0.72156862745098038, 0.88235294117647056, 0.52549019607843139),
+ (0.49803921568627452, 0.73725490196078436, 0.25490196078431371),
+ (0.30196078431372547, 0.5725490196078431 , 0.12941176470588237),
+ (0.15294117647058825, 0.39215686274509803, 0.09803921568627451)
+ )
+
+_PRGn_data = (
+ (0.25098039215686274, 0.0 , 0.29411764705882354),
+ (0.46274509803921571, 0.16470588235294117, 0.51372549019607838),
+ (0.6 , 0.4392156862745098 , 0.6705882352941176 ),
+ (0.76078431372549016, 0.6470588235294118 , 0.81176470588235294),
+ (0.90588235294117647, 0.83137254901960789, 0.90980392156862744),
+ (0.96862745098039216, 0.96862745098039216, 0.96862745098039216),
+ (0.85098039215686272, 0.94117647058823528, 0.82745098039215681),
+ (0.65098039215686276, 0.85882352941176465, 0.62745098039215685),
+ (0.35294117647058826, 0.68235294117647061, 0.38039215686274508),
+ (0.10588235294117647, 0.47058823529411764, 0.21568627450980393),
+ (0.0 , 0.26666666666666666, 0.10588235294117647)
+ )
+
+_PuBu_data = (
+ (1.0 , 0.96862745098039216, 0.98431372549019602),
+ (0.92549019607843142, 0.90588235294117647, 0.94901960784313721),
+ (0.81568627450980391, 0.81960784313725488, 0.90196078431372551),
+ (0.65098039215686276, 0.74117647058823533, 0.85882352941176465),
+ (0.45490196078431372, 0.66274509803921566, 0.81176470588235294),
+ (0.21176470588235294, 0.56470588235294117, 0.75294117647058822),
+ (0.0196078431372549 , 0.4392156862745098 , 0.69019607843137254),
+ (0.01568627450980392, 0.35294117647058826, 0.55294117647058827),
+ (0.00784313725490196, 0.2196078431372549 , 0.34509803921568627)
+ )
+
+_PuBuGn_data = (
+ (1.0 , 0.96862745098039216, 0.98431372549019602),
+ (0.92549019607843142, 0.88627450980392153, 0.94117647058823528),
+ (0.81568627450980391, 0.81960784313725488, 0.90196078431372551),
+ (0.65098039215686276, 0.74117647058823533, 0.85882352941176465),
+ (0.40392156862745099, 0.66274509803921566, 0.81176470588235294),
+ (0.21176470588235294, 0.56470588235294117, 0.75294117647058822),
+ (0.00784313725490196, 0.50588235294117645, 0.54117647058823526),
+ (0.00392156862745098, 0.42352941176470588, 0.34901960784313724),
+ (0.00392156862745098, 0.27450980392156865, 0.21176470588235294)
+ )
+
+_PuOr_data = (
+ (0.49803921568627452, 0.23137254901960785, 0.03137254901960784),
+ (0.70196078431372544, 0.34509803921568627, 0.02352941176470588),
+ (0.8784313725490196 , 0.50980392156862742, 0.07843137254901961),
+ (0.99215686274509807, 0.72156862745098038, 0.38823529411764707),
+ (0.99607843137254903, 0.8784313725490196 , 0.71372549019607845),
+ (0.96862745098039216, 0.96862745098039216, 0.96862745098039216),
+ (0.84705882352941175, 0.85490196078431369, 0.92156862745098034),
+ (0.69803921568627447, 0.6705882352941176 , 0.82352941176470584),
+ (0.50196078431372548, 0.45098039215686275, 0.67450980392156867),
+ (0.32941176470588235, 0.15294117647058825, 0.53333333333333333),
+ (0.17647058823529413, 0.0 , 0.29411764705882354)
+ )
+
+_PuRd_data = (
+ (0.96862745098039216, 0.95686274509803926, 0.97647058823529409),
+ (0.90588235294117647, 0.88235294117647056, 0.93725490196078431),
+ (0.83137254901960789, 0.72549019607843135, 0.85490196078431369),
+ (0.78823529411764703, 0.58039215686274515, 0.7803921568627451 ),
+ (0.87450980392156863, 0.396078431372549 , 0.69019607843137254),
+ (0.90588235294117647, 0.16078431372549021, 0.54117647058823526),
+ (0.80784313725490198, 0.07058823529411765, 0.33725490196078434),
+ (0.59607843137254901, 0.0 , 0.2627450980392157 ),
+ (0.40392156862745099, 0.0 , 0.12156862745098039)
+ )
+
+_Purples_data = (
+ (0.9882352941176471 , 0.98431372549019602, 0.99215686274509807),
+ (0.93725490196078431, 0.92941176470588238, 0.96078431372549022),
+ (0.85490196078431369, 0.85490196078431369, 0.92156862745098034),
+ (0.73725490196078436, 0.74117647058823533, 0.86274509803921573),
+ (0.61960784313725492, 0.60392156862745094, 0.78431372549019607),
+ (0.50196078431372548, 0.49019607843137253, 0.72941176470588232),
+ (0.41568627450980394, 0.31764705882352939, 0.63921568627450975),
+ (0.32941176470588235, 0.15294117647058825, 0.5607843137254902 ),
+ (0.24705882352941178, 0.0 , 0.49019607843137253)
+ )
+
+_RdBu_data = (
+ (0.40392156862745099, 0.0 , 0.12156862745098039),
+ (0.69803921568627447, 0.09411764705882353, 0.16862745098039217),
+ (0.83921568627450982, 0.37647058823529411, 0.30196078431372547),
+ (0.95686274509803926, 0.6470588235294118 , 0.50980392156862742),
+ (0.99215686274509807, 0.85882352941176465, 0.7803921568627451 ),
+ (0.96862745098039216, 0.96862745098039216, 0.96862745098039216),
+ (0.81960784313725488, 0.89803921568627454, 0.94117647058823528),
+ (0.5725490196078431 , 0.77254901960784317, 0.87058823529411766),
+ (0.2627450980392157 , 0.57647058823529407, 0.76470588235294112),
+ (0.12941176470588237, 0.4 , 0.67450980392156867),
+ (0.0196078431372549 , 0.18823529411764706, 0.38039215686274508)
+ )
+
+_RdGy_data = (
+ (0.40392156862745099, 0.0 , 0.12156862745098039),
+ (0.69803921568627447, 0.09411764705882353, 0.16862745098039217),
+ (0.83921568627450982, 0.37647058823529411, 0.30196078431372547),
+ (0.95686274509803926, 0.6470588235294118 , 0.50980392156862742),
+ (0.99215686274509807, 0.85882352941176465, 0.7803921568627451 ),
+ (1.0 , 1.0 , 1.0 ),
+ (0.8784313725490196 , 0.8784313725490196 , 0.8784313725490196 ),
+ (0.72941176470588232, 0.72941176470588232, 0.72941176470588232),
+ (0.52941176470588236, 0.52941176470588236, 0.52941176470588236),
+ (0.30196078431372547, 0.30196078431372547, 0.30196078431372547),
+ (0.10196078431372549, 0.10196078431372549, 0.10196078431372549)
+ )
+
+_RdPu_data = (
+ (1.0 , 0.96862745098039216, 0.95294117647058818),
+ (0.99215686274509807, 0.8784313725490196 , 0.86666666666666667),
+ (0.9882352941176471 , 0.77254901960784317, 0.75294117647058822),
+ (0.98039215686274506, 0.62352941176470589, 0.70980392156862748),
+ (0.96862745098039216, 0.40784313725490196, 0.63137254901960782),
+ (0.86666666666666667, 0.20392156862745098, 0.59215686274509804),
+ (0.68235294117647061, 0.00392156862745098, 0.49411764705882355),
+ (0.47843137254901963, 0.00392156862745098, 0.46666666666666667),
+ (0.28627450980392155, 0.0 , 0.41568627450980394)
+ )
+
+_RdYlBu_data = (
+ (0.6470588235294118 , 0.0 , 0.14901960784313725),
+ (0.84313725490196079, 0.18823529411764706 , 0.15294117647058825),
+ (0.95686274509803926, 0.42745098039215684 , 0.2627450980392157 ),
+ (0.99215686274509807, 0.68235294117647061 , 0.38039215686274508),
+ (0.99607843137254903, 0.8784313725490196 , 0.56470588235294117),
+ (1.0 , 1.0 , 0.74901960784313726),
+ (0.8784313725490196 , 0.95294117647058818 , 0.97254901960784312),
+ (0.6705882352941176 , 0.85098039215686272 , 0.9137254901960784 ),
+ (0.45490196078431372, 0.67843137254901964 , 0.81960784313725488),
+ (0.27058823529411763, 0.45882352941176469 , 0.70588235294117652),
+ (0.19215686274509805, 0.21176470588235294 , 0.58431372549019611)
+ )
+
+_RdYlGn_data = (
+ (0.6470588235294118 , 0.0 , 0.14901960784313725),
+ (0.84313725490196079, 0.18823529411764706 , 0.15294117647058825),
+ (0.95686274509803926, 0.42745098039215684 , 0.2627450980392157 ),
+ (0.99215686274509807, 0.68235294117647061 , 0.38039215686274508),
+ (0.99607843137254903, 0.8784313725490196 , 0.54509803921568623),
+ (1.0 , 1.0 , 0.74901960784313726),
+ (0.85098039215686272, 0.93725490196078431 , 0.54509803921568623),
+ (0.65098039215686276, 0.85098039215686272 , 0.41568627450980394),
+ (0.4 , 0.74117647058823533 , 0.38823529411764707),
+ (0.10196078431372549, 0.59607843137254901 , 0.31372549019607843),
+ (0.0 , 0.40784313725490196 , 0.21568627450980393)
+ )
+
+_Reds_data = (
+ (1.0 , 0.96078431372549022 , 0.94117647058823528),
+ (0.99607843137254903, 0.8784313725490196 , 0.82352941176470584),
+ (0.9882352941176471 , 0.73333333333333328 , 0.63137254901960782),
+ (0.9882352941176471 , 0.5725490196078431 , 0.44705882352941179),
+ (0.98431372549019602, 0.41568627450980394 , 0.29019607843137257),
+ (0.93725490196078431, 0.23137254901960785 , 0.17254901960784313),
+ (0.79607843137254897, 0.094117647058823528, 0.11372549019607843),
+ (0.6470588235294118 , 0.058823529411764705, 0.08235294117647058),
+ (0.40392156862745099, 0.0 , 0.05098039215686274)
+ )
+
+_Spectral_data = (
+ (0.61960784313725492, 0.003921568627450980, 0.25882352941176473),
+ (0.83529411764705885, 0.24313725490196078 , 0.30980392156862746),
+ (0.95686274509803926, 0.42745098039215684 , 0.2627450980392157 ),
+ (0.99215686274509807, 0.68235294117647061 , 0.38039215686274508),
+ (0.99607843137254903, 0.8784313725490196 , 0.54509803921568623),
+ (1.0 , 1.0 , 0.74901960784313726),
+ (0.90196078431372551, 0.96078431372549022 , 0.59607843137254901),
+ (0.6705882352941176 , 0.8666666666666667 , 0.64313725490196083),
+ (0.4 , 0.76078431372549016 , 0.6470588235294118 ),
+ (0.19607843137254902, 0.53333333333333333 , 0.74117647058823533),
+ (0.36862745098039218, 0.30980392156862746 , 0.63529411764705879)
+ )
+
+_YlGn_data = (
+ (1.0 , 1.0 , 0.89803921568627454),
+ (0.96862745098039216, 0.9882352941176471 , 0.72549019607843135),
+ (0.85098039215686272, 0.94117647058823528 , 0.63921568627450975),
+ (0.67843137254901964, 0.8666666666666667 , 0.55686274509803924),
+ (0.47058823529411764, 0.77647058823529413 , 0.47450980392156861),
+ (0.25490196078431371, 0.6705882352941176 , 0.36470588235294116),
+ (0.13725490196078433, 0.51764705882352946 , 0.2627450980392157 ),
+ (0.0 , 0.40784313725490196 , 0.21568627450980393),
+ (0.0 , 0.27058823529411763 , 0.16078431372549021)
+ )
+
+_YlGnBu_data = (
+ (1.0 , 1.0 , 0.85098039215686272),
+ (0.92941176470588238, 0.97254901960784312 , 0.69411764705882351),
+ (0.7803921568627451 , 0.9137254901960784 , 0.70588235294117652),
+ (0.49803921568627452, 0.80392156862745101 , 0.73333333333333328),
+ (0.25490196078431371, 0.71372549019607845 , 0.7686274509803922 ),
+ (0.11372549019607843, 0.56862745098039214 , 0.75294117647058822),
+ (0.13333333333333333, 0.36862745098039218 , 0.6588235294117647 ),
+ (0.14509803921568629, 0.20392156862745098 , 0.58039215686274515),
+ (0.03137254901960784, 0.11372549019607843 , 0.34509803921568627)
+ )
+
+_YlOrBr_data = (
+ (1.0 , 1.0 , 0.89803921568627454),
+ (1.0 , 0.96862745098039216 , 0.73725490196078436),
+ (0.99607843137254903, 0.8901960784313725 , 0.56862745098039214),
+ (0.99607843137254903, 0.7686274509803922 , 0.30980392156862746),
+ (0.99607843137254903, 0.6 , 0.16078431372549021),
+ (0.92549019607843142, 0.4392156862745098 , 0.07843137254901961),
+ (0.8 , 0.29803921568627451 , 0.00784313725490196),
+ (0.6 , 0.20392156862745098 , 0.01568627450980392),
+ (0.4 , 0.14509803921568629 , 0.02352941176470588)
+ )
+
+_YlOrRd_data = (
+ (1.0 , 1.0 , 0.8 ),
+ (1.0 , 0.92941176470588238 , 0.62745098039215685),
+ (0.99607843137254903, 0.85098039215686272 , 0.46274509803921571),
+ (0.99607843137254903, 0.69803921568627447 , 0.29803921568627451),
+ (0.99215686274509807, 0.55294117647058827 , 0.23529411764705882),
+ (0.9882352941176471 , 0.30588235294117649 , 0.16470588235294117),
+ (0.8901960784313725 , 0.10196078431372549 , 0.10980392156862745),
+ (0.74117647058823533, 0.0 , 0.14901960784313725),
+ (0.50196078431372548, 0.0 , 0.14901960784313725)
+ )
+
+
+# ColorBrewer's qualitative maps, implemented using ListedColormap
+# for use with mpl.colors.NoNorm
+
+_Accent_data = (
+ (0.49803921568627452, 0.78823529411764703, 0.49803921568627452),
+ (0.74509803921568629, 0.68235294117647061, 0.83137254901960789),
+ (0.99215686274509807, 0.75294117647058822, 0.52549019607843139),
+ (1.0, 1.0, 0.6 ),
+ (0.2196078431372549, 0.42352941176470588, 0.69019607843137254),
+ (0.94117647058823528, 0.00784313725490196, 0.49803921568627452),
+ (0.74901960784313726, 0.35686274509803922, 0.09019607843137254),
+ (0.4, 0.4, 0.4 ),
+ )
+
+_Dark2_data = (
+ (0.10588235294117647, 0.61960784313725492, 0.46666666666666667),
+ (0.85098039215686272, 0.37254901960784315, 0.00784313725490196),
+ (0.45882352941176469, 0.4392156862745098, 0.70196078431372544),
+ (0.90588235294117647, 0.16078431372549021, 0.54117647058823526),
+ (0.4, 0.65098039215686276, 0.11764705882352941),
+ (0.90196078431372551, 0.6705882352941176, 0.00784313725490196),
+ (0.65098039215686276, 0.46274509803921571, 0.11372549019607843),
+ (0.4, 0.4, 0.4 ),
+ )
+
+_Paired_data = (
+ (0.65098039215686276, 0.80784313725490198, 0.8901960784313725 ),
+ (0.12156862745098039, 0.47058823529411764, 0.70588235294117652),
+ (0.69803921568627447, 0.87450980392156863, 0.54117647058823526),
+ (0.2, 0.62745098039215685, 0.17254901960784313),
+ (0.98431372549019602, 0.60392156862745094, 0.6 ),
+ (0.8901960784313725, 0.10196078431372549, 0.10980392156862745),
+ (0.99215686274509807, 0.74901960784313726, 0.43529411764705883),
+ (1.0, 0.49803921568627452, 0.0 ),
+ (0.792156862745098, 0.69803921568627447, 0.83921568627450982),
+ (0.41568627450980394, 0.23921568627450981, 0.60392156862745094),
+ (1.0, 1.0, 0.6 ),
+ (0.69411764705882351, 0.34901960784313724, 0.15686274509803921),
+ )
+
+_Pastel1_data = (
+ (0.98431372549019602, 0.70588235294117652, 0.68235294117647061),
+ (0.70196078431372544, 0.80392156862745101, 0.8901960784313725 ),
+ (0.8, 0.92156862745098034, 0.77254901960784317),
+ (0.87058823529411766, 0.79607843137254897, 0.89411764705882357),
+ (0.99607843137254903, 0.85098039215686272, 0.65098039215686276),
+ (1.0, 1.0, 0.8 ),
+ (0.89803921568627454, 0.84705882352941175, 0.74117647058823533),
+ (0.99215686274509807, 0.85490196078431369, 0.92549019607843142),
+ (0.94901960784313721, 0.94901960784313721, 0.94901960784313721),
+ )
+
+_Pastel2_data = (
+ (0.70196078431372544, 0.88627450980392153, 0.80392156862745101),
+ (0.99215686274509807, 0.80392156862745101, 0.67450980392156867),
+ (0.79607843137254897, 0.83529411764705885, 0.90980392156862744),
+ (0.95686274509803926, 0.792156862745098, 0.89411764705882357),
+ (0.90196078431372551, 0.96078431372549022, 0.78823529411764703),
+ (1.0, 0.94901960784313721, 0.68235294117647061),
+ (0.94509803921568625, 0.88627450980392153, 0.8 ),
+ (0.8, 0.8, 0.8 ),
+ )
+
+_Set1_data = (
+ (0.89411764705882357, 0.10196078431372549, 0.10980392156862745),
+ (0.21568627450980393, 0.49411764705882355, 0.72156862745098038),
+ (0.30196078431372547, 0.68627450980392157, 0.29019607843137257),
+ (0.59607843137254901, 0.30588235294117649, 0.63921568627450975),
+ (1.0, 0.49803921568627452, 0.0 ),
+ (1.0, 1.0, 0.2 ),
+ (0.65098039215686276, 0.33725490196078434, 0.15686274509803921),
+ (0.96862745098039216, 0.50588235294117645, 0.74901960784313726),
+ (0.6, 0.6, 0.6),
+ )
+
+_Set2_data = (
+ (0.4, 0.76078431372549016, 0.6470588235294118 ),
+ (0.9882352941176471, 0.55294117647058827, 0.3843137254901961 ),
+ (0.55294117647058827, 0.62745098039215685, 0.79607843137254897),
+ (0.90588235294117647, 0.54117647058823526, 0.76470588235294112),
+ (0.65098039215686276, 0.84705882352941175, 0.32941176470588235),
+ (1.0, 0.85098039215686272, 0.18431372549019609),
+ (0.89803921568627454, 0.7686274509803922, 0.58039215686274515),
+ (0.70196078431372544, 0.70196078431372544, 0.70196078431372544),
+ )
+
+_Set3_data = (
+ (0.55294117647058827, 0.82745098039215681, 0.7803921568627451 ),
+ (1.0, 1.0, 0.70196078431372544),
+ (0.74509803921568629, 0.72941176470588232, 0.85490196078431369),
+ (0.98431372549019602, 0.50196078431372548, 0.44705882352941179),
+ (0.50196078431372548, 0.69411764705882351, 0.82745098039215681),
+ (0.99215686274509807, 0.70588235294117652, 0.3843137254901961 ),
+ (0.70196078431372544, 0.87058823529411766, 0.41176470588235292),
+ (0.9882352941176471, 0.80392156862745101, 0.89803921568627454),
+ (0.85098039215686272, 0.85098039215686272, 0.85098039215686272),
+ (0.73725490196078436, 0.50196078431372548, 0.74117647058823533),
+ (0.8, 0.92156862745098034, 0.77254901960784317),
+ (1.0, 0.92941176470588238, 0.43529411764705883),
+ )
+
+
+# The next 7 palettes are from the Yorick scientific visualization package,
+# an evolution of the GIST package, both by David H. Munro.
+# They are released under a BSD-like license (see LICENSE_YORICK in
+# the license directory of the matplotlib source distribution).
+#
+# Most palette functions have been reduced to simple function descriptions
+# by Reinier Heeres, since the rgb components were mostly straight lines.
+# gist_earth_data and gist_ncar_data were simplified by a script and some
+# manual effort.
+
+_gist_earth_data = {
+ 'red': (
+ (0.0, 0.0, 0.0000),
+ (0.2824, 0.1882, 0.1882),
+ (0.4588, 0.2714, 0.2714),
+ (0.5490, 0.4719, 0.4719),
+ (0.6980, 0.7176, 0.7176),
+ (0.7882, 0.7553, 0.7553),
+ (1.0000, 0.9922, 0.9922),
+ ),
+ 'green': (
+ (0.0, 0.0, 0.0000),
+ (0.0275, 0.0000, 0.0000),
+ (0.1098, 0.1893, 0.1893),
+ (0.1647, 0.3035, 0.3035),
+ (0.2078, 0.3841, 0.3841),
+ (0.2824, 0.5020, 0.5020),
+ (0.5216, 0.6397, 0.6397),
+ (0.6980, 0.7171, 0.7171),
+ (0.7882, 0.6392, 0.6392),
+ (0.7922, 0.6413, 0.6413),
+ (0.8000, 0.6447, 0.6447),
+ (0.8078, 0.6481, 0.6481),
+ (0.8157, 0.6549, 0.6549),
+ (0.8667, 0.6991, 0.6991),
+ (0.8745, 0.7103, 0.7103),
+ (0.8824, 0.7216, 0.7216),
+ (0.8902, 0.7323, 0.7323),
+ (0.8980, 0.7430, 0.7430),
+ (0.9412, 0.8275, 0.8275),
+ (0.9569, 0.8635, 0.8635),
+ (0.9647, 0.8816, 0.8816),
+ (0.9961, 0.9733, 0.9733),
+ (1.0000, 0.9843, 0.9843),
+ ),
+ 'blue': (
+ (0.0, 0.0, 0.0000),
+ (0.0039, 0.1684, 0.1684),
+ (0.0078, 0.2212, 0.2212),
+ (0.0275, 0.4329, 0.4329),
+ (0.0314, 0.4549, 0.4549),
+ (0.2824, 0.5004, 0.5004),
+ (0.4667, 0.2748, 0.2748),
+ (0.5451, 0.3205, 0.3205),
+ (0.7843, 0.3961, 0.3961),
+ (0.8941, 0.6651, 0.6651),
+ (1.0000, 0.9843, 0.9843),
+ )
+}
+
+_gist_gray_data = {
+ 'red': gfunc[3],
+ 'green': gfunc[3],
+ 'blue': gfunc[3],
+}
+
+def _gist_heat_red(x): return 1.5 * x
+def _gist_heat_green(x): return 2 * x - 1
+def _gist_heat_blue(x): return 4 * x - 3
+_gist_heat_data = {
+ 'red': _gist_heat_red, 'green': _gist_heat_green, 'blue': _gist_heat_blue}
+
+_gist_ncar_data = {
+ 'red': (
+ (0.0, 0.0, 0.0000),
+ (0.3098, 0.0000, 0.0000),
+ (0.3725, 0.3993, 0.3993),
+ (0.4235, 0.5003, 0.5003),
+ (0.5333, 1.0000, 1.0000),
+ (0.7922, 1.0000, 1.0000),
+ (0.8471, 0.6218, 0.6218),
+ (0.8980, 0.9235, 0.9235),
+ (1.0000, 0.9961, 0.9961),
+ ),
+ 'green': (
+ (0.0, 0.0, 0.0000),
+ (0.0510, 0.3722, 0.3722),
+ (0.1059, 0.0000, 0.0000),
+ (0.1569, 0.7202, 0.7202),
+ (0.1608, 0.7537, 0.7537),
+ (0.1647, 0.7752, 0.7752),
+ (0.2157, 1.0000, 1.0000),
+ (0.2588, 0.9804, 0.9804),
+ (0.2706, 0.9804, 0.9804),
+ (0.3176, 1.0000, 1.0000),
+ (0.3686, 0.8081, 0.8081),
+ (0.4275, 1.0000, 1.0000),
+ (0.5216, 1.0000, 1.0000),
+ (0.6314, 0.7292, 0.7292),
+ (0.6863, 0.2796, 0.2796),
+ (0.7451, 0.0000, 0.0000),
+ (0.7922, 0.0000, 0.0000),
+ (0.8431, 0.1753, 0.1753),
+ (0.8980, 0.5000, 0.5000),
+ (1.0000, 0.9725, 0.9725),
+ ),
+ 'blue': (
+ (0.0, 0.5020, 0.5020),
+ (0.0510, 0.0222, 0.0222),
+ (0.1098, 1.0000, 1.0000),
+ (0.2039, 1.0000, 1.0000),
+ (0.2627, 0.6145, 0.6145),
+ (0.3216, 0.0000, 0.0000),
+ (0.4157, 0.0000, 0.0000),
+ (0.4745, 0.2342, 0.2342),
+ (0.5333, 0.0000, 0.0000),
+ (0.5804, 0.0000, 0.0000),
+ (0.6314, 0.0549, 0.0549),
+ (0.6902, 0.0000, 0.0000),
+ (0.7373, 0.0000, 0.0000),
+ (0.7922, 0.9738, 0.9738),
+ (0.8000, 1.0000, 1.0000),
+ (0.8431, 1.0000, 1.0000),
+ (0.8980, 0.9341, 0.9341),
+ (1.0000, 0.9961, 0.9961),
+ )
+}
+
+_gist_rainbow_data = (
+ (0.000, (1.00, 0.00, 0.16)),
+ (0.030, (1.00, 0.00, 0.00)),
+ (0.215, (1.00, 1.00, 0.00)),
+ (0.400, (0.00, 1.00, 0.00)),
+ (0.586, (0.00, 1.00, 1.00)),
+ (0.770, (0.00, 0.00, 1.00)),
+ (0.954, (1.00, 0.00, 1.00)),
+ (1.000, (1.00, 0.00, 0.75))
+)
+
+_gist_stern_data = {
+ 'red': (
+ (0.000, 0.000, 0.000), (0.0547, 1.000, 1.000),
+ (0.250, 0.027, 0.250), # (0.2500, 0.250, 0.250),
+ (1.000, 1.000, 1.000)),
+ 'green': ((0, 0, 0), (1, 1, 1)),
+ 'blue': (
+ (0.000, 0.000, 0.000), (0.500, 1.000, 1.000),
+ (0.735, 0.000, 0.000), (1.000, 1.000, 1.000))
+}
+
+def _gist_yarg(x): return 1 - x
+_gist_yarg_data = {'red': _gist_yarg, 'green': _gist_yarg, 'blue': _gist_yarg}
+
+# This bipolar colormap was generated from CoolWarmFloat33.csv of
+# "Diverging Color Maps for Scientific Visualization" by Kenneth Moreland.
+#
+_coolwarm_data = {
+ 'red': [
+ (0.0, 0.2298057, 0.2298057),
+ (0.03125, 0.26623388, 0.26623388),
+ (0.0625, 0.30386891, 0.30386891),
+ (0.09375, 0.342804478, 0.342804478),
+ (0.125, 0.38301334, 0.38301334),
+ (0.15625, 0.424369608, 0.424369608),
+ (0.1875, 0.46666708, 0.46666708),
+ (0.21875, 0.509635204, 0.509635204),
+ (0.25, 0.552953156, 0.552953156),
+ (0.28125, 0.596262162, 0.596262162),
+ (0.3125, 0.639176211, 0.639176211),
+ (0.34375, 0.681291281, 0.681291281),
+ (0.375, 0.722193294, 0.722193294),
+ (0.40625, 0.761464949, 0.761464949),
+ (0.4375, 0.798691636, 0.798691636),
+ (0.46875, 0.833466556, 0.833466556),
+ (0.5, 0.865395197, 0.865395197),
+ (0.53125, 0.897787179, 0.897787179),
+ (0.5625, 0.924127593, 0.924127593),
+ (0.59375, 0.944468518, 0.944468518),
+ (0.625, 0.958852946, 0.958852946),
+ (0.65625, 0.96732803, 0.96732803),
+ (0.6875, 0.969954137, 0.969954137),
+ (0.71875, 0.966811177, 0.966811177),
+ (0.75, 0.958003065, 0.958003065),
+ (0.78125, 0.943660866, 0.943660866),
+ (0.8125, 0.923944917, 0.923944917),
+ (0.84375, 0.89904617, 0.89904617),
+ (0.875, 0.869186849, 0.869186849),
+ (0.90625, 0.834620542, 0.834620542),
+ (0.9375, 0.795631745, 0.795631745),
+ (0.96875, 0.752534934, 0.752534934),
+ (1.0, 0.705673158, 0.705673158)],
+ 'green': [
+ (0.0, 0.298717966, 0.298717966),
+ (0.03125, 0.353094838, 0.353094838),
+ (0.0625, 0.406535296, 0.406535296),
+ (0.09375, 0.458757618, 0.458757618),
+ (0.125, 0.50941904, 0.50941904),
+ (0.15625, 0.558148092, 0.558148092),
+ (0.1875, 0.604562568, 0.604562568),
+ (0.21875, 0.648280772, 0.648280772),
+ (0.25, 0.688929332, 0.688929332),
+ (0.28125, 0.726149107, 0.726149107),
+ (0.3125, 0.759599947, 0.759599947),
+ (0.34375, 0.788964712, 0.788964712),
+ (0.375, 0.813952739, 0.813952739),
+ (0.40625, 0.834302879, 0.834302879),
+ (0.4375, 0.849786142, 0.849786142),
+ (0.46875, 0.860207984, 0.860207984),
+ (0.5, 0.86541021, 0.86541021),
+ (0.53125, 0.848937047, 0.848937047),
+ (0.5625, 0.827384882, 0.827384882),
+ (0.59375, 0.800927443, 0.800927443),
+ (0.625, 0.769767752, 0.769767752),
+ (0.65625, 0.734132809, 0.734132809),
+ (0.6875, 0.694266682, 0.694266682),
+ (0.71875, 0.650421156, 0.650421156),
+ (0.75, 0.602842431, 0.602842431),
+ (0.78125, 0.551750968, 0.551750968),
+ (0.8125, 0.49730856, 0.49730856),
+ (0.84375, 0.439559467, 0.439559467),
+ (0.875, 0.378313092, 0.378313092),
+ (0.90625, 0.312874446, 0.312874446),
+ (0.9375, 0.24128379, 0.24128379),
+ (0.96875, 0.157246067, 0.157246067),
+ (1.0, 0.01555616, 0.01555616)],
+ 'blue': [
+ (0.0, 0.753683153, 0.753683153),
+ (0.03125, 0.801466763, 0.801466763),
+ (0.0625, 0.84495867, 0.84495867),
+ (0.09375, 0.883725899, 0.883725899),
+ (0.125, 0.917387822, 0.917387822),
+ (0.15625, 0.945619588, 0.945619588),
+ (0.1875, 0.968154911, 0.968154911),
+ (0.21875, 0.98478814, 0.98478814),
+ (0.25, 0.995375608, 0.995375608),
+ (0.28125, 0.999836203, 0.999836203),
+ (0.3125, 0.998151185, 0.998151185),
+ (0.34375, 0.990363227, 0.990363227),
+ (0.375, 0.976574709, 0.976574709),
+ (0.40625, 0.956945269, 0.956945269),
+ (0.4375, 0.931688648, 0.931688648),
+ (0.46875, 0.901068838, 0.901068838),
+ (0.5, 0.865395561, 0.865395561),
+ (0.53125, 0.820880546, 0.820880546),
+ (0.5625, 0.774508472, 0.774508472),
+ (0.59375, 0.726736146, 0.726736146),
+ (0.625, 0.678007945, 0.678007945),
+ (0.65625, 0.628751763, 0.628751763),
+ (0.6875, 0.579375448, 0.579375448),
+ (0.71875, 0.530263762, 0.530263762),
+ (0.75, 0.481775914, 0.481775914),
+ (0.78125, 0.434243684, 0.434243684),
+ (0.8125, 0.387970225, 0.387970225),
+ (0.84375, 0.343229596, 0.343229596),
+ (0.875, 0.300267182, 0.300267182),
+ (0.90625, 0.259301199, 0.259301199),
+ (0.9375, 0.220525627, 0.220525627),
+ (0.96875, 0.184115123, 0.184115123),
+ (1.0, 0.150232812, 0.150232812)]
+ }
+
+# Implementation of Carey Rappaport's CMRmap.
+# See `A Color Map for Effective Black-and-White Rendering of Color-Scale
+# Images' by Carey Rappaport
+# https://www.mathworks.com/matlabcentral/fileexchange/2662-cmrmap-m
+_CMRmap_data = {'red': ((0.000, 0.00, 0.00),
+ (0.125, 0.15, 0.15),
+ (0.250, 0.30, 0.30),
+ (0.375, 0.60, 0.60),
+ (0.500, 1.00, 1.00),
+ (0.625, 0.90, 0.90),
+ (0.750, 0.90, 0.90),
+ (0.875, 0.90, 0.90),
+ (1.000, 1.00, 1.00)),
+ 'green': ((0.000, 0.00, 0.00),
+ (0.125, 0.15, 0.15),
+ (0.250, 0.15, 0.15),
+ (0.375, 0.20, 0.20),
+ (0.500, 0.25, 0.25),
+ (0.625, 0.50, 0.50),
+ (0.750, 0.75, 0.75),
+ (0.875, 0.90, 0.90),
+ (1.000, 1.00, 1.00)),
+ 'blue': ((0.000, 0.00, 0.00),
+ (0.125, 0.50, 0.50),
+ (0.250, 0.75, 0.75),
+ (0.375, 0.50, 0.50),
+ (0.500, 0.15, 0.15),
+ (0.625, 0.00, 0.00),
+ (0.750, 0.10, 0.10),
+ (0.875, 0.50, 0.50),
+ (1.000, 1.00, 1.00))}
+
+
+# An MIT licensed, colorblind-friendly heatmap from Wistia:
+# https://github.com/wistia/heatmap-palette
+# https://wistia.com/learn/culture/heatmaps-for-colorblindness
+#
+# >>> import matplotlib.colors as c
+# >>> colors = ["#e4ff7a", "#ffe81a", "#ffbd00", "#ffa000", "#fc7f00"]
+# >>> cm = c.LinearSegmentedColormap.from_list('wistia', colors)
+# >>> _wistia_data = cm._segmentdata
+# >>> del _wistia_data['alpha']
+#
+_wistia_data = {
+ 'red': [(0.0, 0.8941176470588236, 0.8941176470588236),
+ (0.25, 1.0, 1.0),
+ (0.5, 1.0, 1.0),
+ (0.75, 1.0, 1.0),
+ (1.0, 0.9882352941176471, 0.9882352941176471)],
+ 'green': [(0.0, 1.0, 1.0),
+ (0.25, 0.9098039215686274, 0.9098039215686274),
+ (0.5, 0.7411764705882353, 0.7411764705882353),
+ (0.75, 0.6274509803921569, 0.6274509803921569),
+ (1.0, 0.4980392156862745, 0.4980392156862745)],
+ 'blue': [(0.0, 0.47843137254901963, 0.47843137254901963),
+ (0.25, 0.10196078431372549, 0.10196078431372549),
+ (0.5, 0.0, 0.0),
+ (0.75, 0.0, 0.0),
+ (1.0, 0.0, 0.0)],
+}
+
+
+# Categorical palettes from Vega:
+# https://github.com/vega/vega/wiki/Scales
+# (divided by 255)
+#
+
+_tab10_data = (
+ (0.12156862745098039, 0.4666666666666667, 0.7058823529411765 ), # 1f77b4
+ (1.0, 0.4980392156862745, 0.054901960784313725), # ff7f0e
+ (0.17254901960784313, 0.6274509803921569, 0.17254901960784313 ), # 2ca02c
+ (0.8392156862745098, 0.15294117647058825, 0.1568627450980392 ), # d62728
+ (0.5803921568627451, 0.403921568627451, 0.7411764705882353 ), # 9467bd
+ (0.5490196078431373, 0.33725490196078434, 0.29411764705882354 ), # 8c564b
+ (0.8901960784313725, 0.4666666666666667, 0.7607843137254902 ), # e377c2
+ (0.4980392156862745, 0.4980392156862745, 0.4980392156862745 ), # 7f7f7f
+ (0.7372549019607844, 0.7411764705882353, 0.13333333333333333 ), # bcbd22
+ (0.09019607843137255, 0.7450980392156863, 0.8117647058823529), # 17becf
+)
+
+_tab20_data = (
+ (0.12156862745098039, 0.4666666666666667, 0.7058823529411765 ), # 1f77b4
+ (0.6823529411764706, 0.7803921568627451, 0.9098039215686274 ), # aec7e8
+ (1.0, 0.4980392156862745, 0.054901960784313725), # ff7f0e
+ (1.0, 0.7333333333333333, 0.47058823529411764 ), # ffbb78
+ (0.17254901960784313, 0.6274509803921569, 0.17254901960784313 ), # 2ca02c
+ (0.596078431372549, 0.8745098039215686, 0.5411764705882353 ), # 98df8a
+ (0.8392156862745098, 0.15294117647058825, 0.1568627450980392 ), # d62728
+ (1.0, 0.596078431372549, 0.5882352941176471 ), # ff9896
+ (0.5803921568627451, 0.403921568627451, 0.7411764705882353 ), # 9467bd
+ (0.7725490196078432, 0.6901960784313725, 0.8352941176470589 ), # c5b0d5
+ (0.5490196078431373, 0.33725490196078434, 0.29411764705882354 ), # 8c564b
+ (0.7686274509803922, 0.611764705882353, 0.5803921568627451 ), # c49c94
+ (0.8901960784313725, 0.4666666666666667, 0.7607843137254902 ), # e377c2
+ (0.9686274509803922, 0.7137254901960784, 0.8235294117647058 ), # f7b6d2
+ (0.4980392156862745, 0.4980392156862745, 0.4980392156862745 ), # 7f7f7f
+ (0.7803921568627451, 0.7803921568627451, 0.7803921568627451 ), # c7c7c7
+ (0.7372549019607844, 0.7411764705882353, 0.13333333333333333 ), # bcbd22
+ (0.8588235294117647, 0.8588235294117647, 0.5529411764705883 ), # dbdb8d
+ (0.09019607843137255, 0.7450980392156863, 0.8117647058823529 ), # 17becf
+ (0.6196078431372549, 0.8549019607843137, 0.8980392156862745), # 9edae5
+)
+
+_tab20b_data = (
+ (0.2235294117647059, 0.23137254901960785, 0.4745098039215686 ), # 393b79
+ (0.3215686274509804, 0.32941176470588235, 0.6392156862745098 ), # 5254a3
+ (0.4196078431372549, 0.43137254901960786, 0.8117647058823529 ), # 6b6ecf
+ (0.611764705882353, 0.6196078431372549, 0.8705882352941177 ), # 9c9ede
+ (0.38823529411764707, 0.4745098039215686, 0.2235294117647059 ), # 637939
+ (0.5490196078431373, 0.6352941176470588, 0.3215686274509804 ), # 8ca252
+ (0.7098039215686275, 0.8117647058823529, 0.4196078431372549 ), # b5cf6b
+ (0.807843137254902, 0.8588235294117647, 0.611764705882353 ), # cedb9c
+ (0.5490196078431373, 0.42745098039215684, 0.19215686274509805), # 8c6d31
+ (0.7411764705882353, 0.6196078431372549, 0.2235294117647059 ), # bd9e39
+ (0.9058823529411765, 0.7294117647058823, 0.3215686274509804 ), # e7ba52
+ (0.9058823529411765, 0.796078431372549, 0.5803921568627451 ), # e7cb94
+ (0.5176470588235295, 0.23529411764705882, 0.2235294117647059 ), # 843c39
+ (0.6784313725490196, 0.28627450980392155, 0.2901960784313726 ), # ad494a
+ (0.8392156862745098, 0.3803921568627451, 0.4196078431372549 ), # d6616b
+ (0.9058823529411765, 0.5882352941176471, 0.611764705882353 ), # e7969c
+ (0.4823529411764706, 0.2549019607843137, 0.45098039215686275), # 7b4173
+ (0.6470588235294118, 0.3176470588235294, 0.5803921568627451 ), # a55194
+ (0.807843137254902, 0.42745098039215684, 0.7411764705882353 ), # ce6dbd
+ (0.8705882352941177, 0.6196078431372549, 0.8392156862745098 ), # de9ed6
+)
+
+_tab20c_data = (
+ (0.19215686274509805, 0.5098039215686274, 0.7411764705882353 ), # 3182bd
+ (0.4196078431372549, 0.6823529411764706, 0.8392156862745098 ), # 6baed6
+ (0.6196078431372549, 0.792156862745098, 0.8823529411764706 ), # 9ecae1
+ (0.7764705882352941, 0.8588235294117647, 0.9372549019607843 ), # c6dbef
+ (0.9019607843137255, 0.3333333333333333, 0.050980392156862744), # e6550d
+ (0.9921568627450981, 0.5529411764705883, 0.23529411764705882 ), # fd8d3c
+ (0.9921568627450981, 0.6823529411764706, 0.4196078431372549 ), # fdae6b
+ (0.9921568627450981, 0.8156862745098039, 0.6352941176470588 ), # fdd0a2
+ (0.19215686274509805, 0.6392156862745098, 0.32941176470588235 ), # 31a354
+ (0.4549019607843137, 0.7686274509803922, 0.4627450980392157 ), # 74c476
+ (0.6313725490196078, 0.8509803921568627, 0.6078431372549019 ), # a1d99b
+ (0.7803921568627451, 0.9137254901960784, 0.7529411764705882 ), # c7e9c0
+ (0.4588235294117647, 0.4196078431372549, 0.6941176470588235 ), # 756bb1
+ (0.6196078431372549, 0.6039215686274509, 0.7843137254901961 ), # 9e9ac8
+ (0.7372549019607844, 0.7411764705882353, 0.8627450980392157 ), # bcbddc
+ (0.8549019607843137, 0.8549019607843137, 0.9215686274509803 ), # dadaeb
+ (0.38823529411764707, 0.38823529411764707, 0.38823529411764707 ), # 636363
+ (0.5882352941176471, 0.5882352941176471, 0.5882352941176471 ), # 969696
+ (0.7411764705882353, 0.7411764705882353, 0.7411764705882353 ), # bdbdbd
+ (0.8509803921568627, 0.8509803921568627, 0.8509803921568627 ), # d9d9d9
+)
+
+
+_petroff10_data = (
+ (0.24705882352941178, 0.5647058823529412, 0.8549019607843137), # 3f90da
+ (1.0, 0.6627450980392157, 0.054901960784313725), # ffa90e
+ (0.7411764705882353, 0.12156862745098039, 0.00392156862745098), # bd1f01
+ (0.5803921568627451, 0.6431372549019608, 0.6352941176470588), # 94a4a2
+ (0.5137254901960784, 0.17647058823529413, 0.7137254901960784), # 832db6
+ (0.6627450980392157, 0.4196078431372549, 0.34901960784313724), # a96b59
+ (0.9058823529411765, 0.38823529411764707, 0.0), # e76300
+ (0.7254901960784313, 0.6745098039215687, 0.4392156862745098), # b9ac70
+ (0.44313725490196076, 0.4588235294117647, 0.5058823529411764), # 717581
+ (0.5725490196078431, 0.8549019607843137, 0.8666666666666667), # 92dadd
+)
+
+
+datad = {
+ 'Blues': _Blues_data,
+ 'BrBG': _BrBG_data,
+ 'BuGn': _BuGn_data,
+ 'BuPu': _BuPu_data,
+ 'CMRmap': _CMRmap_data,
+ 'GnBu': _GnBu_data,
+ 'Greens': _Greens_data,
+ 'Greys': _Greys_data,
+ 'OrRd': _OrRd_data,
+ 'Oranges': _Oranges_data,
+ 'PRGn': _PRGn_data,
+ 'PiYG': _PiYG_data,
+ 'PuBu': _PuBu_data,
+ 'PuBuGn': _PuBuGn_data,
+ 'PuOr': _PuOr_data,
+ 'PuRd': _PuRd_data,
+ 'Purples': _Purples_data,
+ 'RdBu': _RdBu_data,
+ 'RdGy': _RdGy_data,
+ 'RdPu': _RdPu_data,
+ 'RdYlBu': _RdYlBu_data,
+ 'RdYlGn': _RdYlGn_data,
+ 'Reds': _Reds_data,
+ 'Spectral': _Spectral_data,
+ 'Wistia': _wistia_data,
+ 'YlGn': _YlGn_data,
+ 'YlGnBu': _YlGnBu_data,
+ 'YlOrBr': _YlOrBr_data,
+ 'YlOrRd': _YlOrRd_data,
+ 'afmhot': _afmhot_data,
+ 'autumn': _autumn_data,
+ 'binary': _binary_data,
+ 'bone': _bone_data,
+ 'brg': _brg_data,
+ 'bwr': _bwr_data,
+ 'cool': _cool_data,
+ 'coolwarm': _coolwarm_data,
+ 'copper': _copper_data,
+ 'cubehelix': _cubehelix_data,
+ 'flag': _flag_data,
+ 'gist_earth': _gist_earth_data,
+ 'gist_gray': _gist_gray_data,
+ 'gist_heat': _gist_heat_data,
+ 'gist_ncar': _gist_ncar_data,
+ 'gist_rainbow': _gist_rainbow_data,
+ 'gist_stern': _gist_stern_data,
+ 'gist_yarg': _gist_yarg_data,
+ 'gnuplot': _gnuplot_data,
+ 'gnuplot2': _gnuplot2_data,
+ 'gray': _gray_data,
+ 'hot': _hot_data,
+ 'hsv': _hsv_data,
+ 'jet': _jet_data,
+ 'nipy_spectral': _nipy_spectral_data,
+ 'ocean': _ocean_data,
+ 'pink': _pink_data,
+ 'prism': _prism_data,
+ 'rainbow': _rainbow_data,
+ 'seismic': _seismic_data,
+ 'spring': _spring_data,
+ 'summer': _summer_data,
+ 'terrain': _terrain_data,
+ 'winter': _winter_data,
+ # Qualitative
+ 'Accent': {'listed': _Accent_data},
+ 'Dark2': {'listed': _Dark2_data},
+ 'Paired': {'listed': _Paired_data},
+ 'Pastel1': {'listed': _Pastel1_data},
+ 'Pastel2': {'listed': _Pastel2_data},
+ 'Set1': {'listed': _Set1_data},
+ 'Set2': {'listed': _Set2_data},
+ 'Set3': {'listed': _Set3_data},
+ 'tab10': {'listed': _tab10_data},
+ 'tab20': {'listed': _tab20_data},
+ 'tab20b': {'listed': _tab20b_data},
+ 'tab20c': {'listed': _tab20c_data},
+}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_cm_bivar.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_cm_bivar.py
new file mode 100644
index 0000000000000000000000000000000000000000..53c0d48d7d6c5d3818a33df783a284e11c16662d
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/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/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_cm_listed.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_cm_listed.py
new file mode 100644
index 0000000000000000000000000000000000000000..b90e0a23acb08a80a71e4911ee6e487f4a297bc4
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_cm_listed.py
@@ -0,0 +1,2847 @@
+from .colors import ListedColormap
+
+_magma_data = [[0.001462, 0.000466, 0.013866],
+ [0.002258, 0.001295, 0.018331],
+ [0.003279, 0.002305, 0.023708],
+ [0.004512, 0.003490, 0.029965],
+ [0.005950, 0.004843, 0.037130],
+ [0.007588, 0.006356, 0.044973],
+ [0.009426, 0.008022, 0.052844],
+ [0.011465, 0.009828, 0.060750],
+ [0.013708, 0.011771, 0.068667],
+ [0.016156, 0.013840, 0.076603],
+ [0.018815, 0.016026, 0.084584],
+ [0.021692, 0.018320, 0.092610],
+ [0.024792, 0.020715, 0.100676],
+ [0.028123, 0.023201, 0.108787],
+ [0.031696, 0.025765, 0.116965],
+ [0.035520, 0.028397, 0.125209],
+ [0.039608, 0.031090, 0.133515],
+ [0.043830, 0.033830, 0.141886],
+ [0.048062, 0.036607, 0.150327],
+ [0.052320, 0.039407, 0.158841],
+ [0.056615, 0.042160, 0.167446],
+ [0.060949, 0.044794, 0.176129],
+ [0.065330, 0.047318, 0.184892],
+ [0.069764, 0.049726, 0.193735],
+ [0.074257, 0.052017, 0.202660],
+ [0.078815, 0.054184, 0.211667],
+ [0.083446, 0.056225, 0.220755],
+ [0.088155, 0.058133, 0.229922],
+ [0.092949, 0.059904, 0.239164],
+ [0.097833, 0.061531, 0.248477],
+ [0.102815, 0.063010, 0.257854],
+ [0.107899, 0.064335, 0.267289],
+ [0.113094, 0.065492, 0.276784],
+ [0.118405, 0.066479, 0.286321],
+ [0.123833, 0.067295, 0.295879],
+ [0.129380, 0.067935, 0.305443],
+ [0.135053, 0.068391, 0.315000],
+ [0.140858, 0.068654, 0.324538],
+ [0.146785, 0.068738, 0.334011],
+ [0.152839, 0.068637, 0.343404],
+ [0.159018, 0.068354, 0.352688],
+ [0.165308, 0.067911, 0.361816],
+ [0.171713, 0.067305, 0.370771],
+ [0.178212, 0.066576, 0.379497],
+ [0.184801, 0.065732, 0.387973],
+ [0.191460, 0.064818, 0.396152],
+ [0.198177, 0.063862, 0.404009],
+ [0.204935, 0.062907, 0.411514],
+ [0.211718, 0.061992, 0.418647],
+ [0.218512, 0.061158, 0.425392],
+ [0.225302, 0.060445, 0.431742],
+ [0.232077, 0.059889, 0.437695],
+ [0.238826, 0.059517, 0.443256],
+ [0.245543, 0.059352, 0.448436],
+ [0.252220, 0.059415, 0.453248],
+ [0.258857, 0.059706, 0.457710],
+ [0.265447, 0.060237, 0.461840],
+ [0.271994, 0.060994, 0.465660],
+ [0.278493, 0.061978, 0.469190],
+ [0.284951, 0.063168, 0.472451],
+ [0.291366, 0.064553, 0.475462],
+ [0.297740, 0.066117, 0.478243],
+ [0.304081, 0.067835, 0.480812],
+ [0.310382, 0.069702, 0.483186],
+ [0.316654, 0.071690, 0.485380],
+ [0.322899, 0.073782, 0.487408],
+ [0.329114, 0.075972, 0.489287],
+ [0.335308, 0.078236, 0.491024],
+ [0.341482, 0.080564, 0.492631],
+ [0.347636, 0.082946, 0.494121],
+ [0.353773, 0.085373, 0.495501],
+ [0.359898, 0.087831, 0.496778],
+ [0.366012, 0.090314, 0.497960],
+ [0.372116, 0.092816, 0.499053],
+ [0.378211, 0.095332, 0.500067],
+ [0.384299, 0.097855, 0.501002],
+ [0.390384, 0.100379, 0.501864],
+ [0.396467, 0.102902, 0.502658],
+ [0.402548, 0.105420, 0.503386],
+ [0.408629, 0.107930, 0.504052],
+ [0.414709, 0.110431, 0.504662],
+ [0.420791, 0.112920, 0.505215],
+ [0.426877, 0.115395, 0.505714],
+ [0.432967, 0.117855, 0.506160],
+ [0.439062, 0.120298, 0.506555],
+ [0.445163, 0.122724, 0.506901],
+ [0.451271, 0.125132, 0.507198],
+ [0.457386, 0.127522, 0.507448],
+ [0.463508, 0.129893, 0.507652],
+ [0.469640, 0.132245, 0.507809],
+ [0.475780, 0.134577, 0.507921],
+ [0.481929, 0.136891, 0.507989],
+ [0.488088, 0.139186, 0.508011],
+ [0.494258, 0.141462, 0.507988],
+ [0.500438, 0.143719, 0.507920],
+ [0.506629, 0.145958, 0.507806],
+ [0.512831, 0.148179, 0.507648],
+ [0.519045, 0.150383, 0.507443],
+ [0.525270, 0.152569, 0.507192],
+ [0.531507, 0.154739, 0.506895],
+ [0.537755, 0.156894, 0.506551],
+ [0.544015, 0.159033, 0.506159],
+ [0.550287, 0.161158, 0.505719],
+ [0.556571, 0.163269, 0.505230],
+ [0.562866, 0.165368, 0.504692],
+ [0.569172, 0.167454, 0.504105],
+ [0.575490, 0.169530, 0.503466],
+ [0.581819, 0.171596, 0.502777],
+ [0.588158, 0.173652, 0.502035],
+ [0.594508, 0.175701, 0.501241],
+ [0.600868, 0.177743, 0.500394],
+ [0.607238, 0.179779, 0.499492],
+ [0.613617, 0.181811, 0.498536],
+ [0.620005, 0.183840, 0.497524],
+ [0.626401, 0.185867, 0.496456],
+ [0.632805, 0.187893, 0.495332],
+ [0.639216, 0.189921, 0.494150],
+ [0.645633, 0.191952, 0.492910],
+ [0.652056, 0.193986, 0.491611],
+ [0.658483, 0.196027, 0.490253],
+ [0.664915, 0.198075, 0.488836],
+ [0.671349, 0.200133, 0.487358],
+ [0.677786, 0.202203, 0.485819],
+ [0.684224, 0.204286, 0.484219],
+ [0.690661, 0.206384, 0.482558],
+ [0.697098, 0.208501, 0.480835],
+ [0.703532, 0.210638, 0.479049],
+ [0.709962, 0.212797, 0.477201],
+ [0.716387, 0.214982, 0.475290],
+ [0.722805, 0.217194, 0.473316],
+ [0.729216, 0.219437, 0.471279],
+ [0.735616, 0.221713, 0.469180],
+ [0.742004, 0.224025, 0.467018],
+ [0.748378, 0.226377, 0.464794],
+ [0.754737, 0.228772, 0.462509],
+ [0.761077, 0.231214, 0.460162],
+ [0.767398, 0.233705, 0.457755],
+ [0.773695, 0.236249, 0.455289],
+ [0.779968, 0.238851, 0.452765],
+ [0.786212, 0.241514, 0.450184],
+ [0.792427, 0.244242, 0.447543],
+ [0.798608, 0.247040, 0.444848],
+ [0.804752, 0.249911, 0.442102],
+ [0.810855, 0.252861, 0.439305],
+ [0.816914, 0.255895, 0.436461],
+ [0.822926, 0.259016, 0.433573],
+ [0.828886, 0.262229, 0.430644],
+ [0.834791, 0.265540, 0.427671],
+ [0.840636, 0.268953, 0.424666],
+ [0.846416, 0.272473, 0.421631],
+ [0.852126, 0.276106, 0.418573],
+ [0.857763, 0.279857, 0.415496],
+ [0.863320, 0.283729, 0.412403],
+ [0.868793, 0.287728, 0.409303],
+ [0.874176, 0.291859, 0.406205],
+ [0.879464, 0.296125, 0.403118],
+ [0.884651, 0.300530, 0.400047],
+ [0.889731, 0.305079, 0.397002],
+ [0.894700, 0.309773, 0.393995],
+ [0.899552, 0.314616, 0.391037],
+ [0.904281, 0.319610, 0.388137],
+ [0.908884, 0.324755, 0.385308],
+ [0.913354, 0.330052, 0.382563],
+ [0.917689, 0.335500, 0.379915],
+ [0.921884, 0.341098, 0.377376],
+ [0.925937, 0.346844, 0.374959],
+ [0.929845, 0.352734, 0.372677],
+ [0.933606, 0.358764, 0.370541],
+ [0.937221, 0.364929, 0.368567],
+ [0.940687, 0.371224, 0.366762],
+ [0.944006, 0.377643, 0.365136],
+ [0.947180, 0.384178, 0.363701],
+ [0.950210, 0.390820, 0.362468],
+ [0.953099, 0.397563, 0.361438],
+ [0.955849, 0.404400, 0.360619],
+ [0.958464, 0.411324, 0.360014],
+ [0.960949, 0.418323, 0.359630],
+ [0.963310, 0.425390, 0.359469],
+ [0.965549, 0.432519, 0.359529],
+ [0.967671, 0.439703, 0.359810],
+ [0.969680, 0.446936, 0.360311],
+ [0.971582, 0.454210, 0.361030],
+ [0.973381, 0.461520, 0.361965],
+ [0.975082, 0.468861, 0.363111],
+ [0.976690, 0.476226, 0.364466],
+ [0.978210, 0.483612, 0.366025],
+ [0.979645, 0.491014, 0.367783],
+ [0.981000, 0.498428, 0.369734],
+ [0.982279, 0.505851, 0.371874],
+ [0.983485, 0.513280, 0.374198],
+ [0.984622, 0.520713, 0.376698],
+ [0.985693, 0.528148, 0.379371],
+ [0.986700, 0.535582, 0.382210],
+ [0.987646, 0.543015, 0.385210],
+ [0.988533, 0.550446, 0.388365],
+ [0.989363, 0.557873, 0.391671],
+ [0.990138, 0.565296, 0.395122],
+ [0.990871, 0.572706, 0.398714],
+ [0.991558, 0.580107, 0.402441],
+ [0.992196, 0.587502, 0.406299],
+ [0.992785, 0.594891, 0.410283],
+ [0.993326, 0.602275, 0.414390],
+ [0.993834, 0.609644, 0.418613],
+ [0.994309, 0.616999, 0.422950],
+ [0.994738, 0.624350, 0.427397],
+ [0.995122, 0.631696, 0.431951],
+ [0.995480, 0.639027, 0.436607],
+ [0.995810, 0.646344, 0.441361],
+ [0.996096, 0.653659, 0.446213],
+ [0.996341, 0.660969, 0.451160],
+ [0.996580, 0.668256, 0.456192],
+ [0.996775, 0.675541, 0.461314],
+ [0.996925, 0.682828, 0.466526],
+ [0.997077, 0.690088, 0.471811],
+ [0.997186, 0.697349, 0.477182],
+ [0.997254, 0.704611, 0.482635],
+ [0.997325, 0.711848, 0.488154],
+ [0.997351, 0.719089, 0.493755],
+ [0.997351, 0.726324, 0.499428],
+ [0.997341, 0.733545, 0.505167],
+ [0.997285, 0.740772, 0.510983],
+ [0.997228, 0.747981, 0.516859],
+ [0.997138, 0.755190, 0.522806],
+ [0.997019, 0.762398, 0.528821],
+ [0.996898, 0.769591, 0.534892],
+ [0.996727, 0.776795, 0.541039],
+ [0.996571, 0.783977, 0.547233],
+ [0.996369, 0.791167, 0.553499],
+ [0.996162, 0.798348, 0.559820],
+ [0.995932, 0.805527, 0.566202],
+ [0.995680, 0.812706, 0.572645],
+ [0.995424, 0.819875, 0.579140],
+ [0.995131, 0.827052, 0.585701],
+ [0.994851, 0.834213, 0.592307],
+ [0.994524, 0.841387, 0.598983],
+ [0.994222, 0.848540, 0.605696],
+ [0.993866, 0.855711, 0.612482],
+ [0.993545, 0.862859, 0.619299],
+ [0.993170, 0.870024, 0.626189],
+ [0.992831, 0.877168, 0.633109],
+ [0.992440, 0.884330, 0.640099],
+ [0.992089, 0.891470, 0.647116],
+ [0.991688, 0.898627, 0.654202],
+ [0.991332, 0.905763, 0.661309],
+ [0.990930, 0.912915, 0.668481],
+ [0.990570, 0.920049, 0.675675],
+ [0.990175, 0.927196, 0.682926],
+ [0.989815, 0.934329, 0.690198],
+ [0.989434, 0.941470, 0.697519],
+ [0.989077, 0.948604, 0.704863],
+ [0.988717, 0.955742, 0.712242],
+ [0.988367, 0.962878, 0.719649],
+ [0.988033, 0.970012, 0.727077],
+ [0.987691, 0.977154, 0.734536],
+ [0.987387, 0.984288, 0.742002],
+ [0.987053, 0.991438, 0.749504]]
+
+_inferno_data = [[0.001462, 0.000466, 0.013866],
+ [0.002267, 0.001270, 0.018570],
+ [0.003299, 0.002249, 0.024239],
+ [0.004547, 0.003392, 0.030909],
+ [0.006006, 0.004692, 0.038558],
+ [0.007676, 0.006136, 0.046836],
+ [0.009561, 0.007713, 0.055143],
+ [0.011663, 0.009417, 0.063460],
+ [0.013995, 0.011225, 0.071862],
+ [0.016561, 0.013136, 0.080282],
+ [0.019373, 0.015133, 0.088767],
+ [0.022447, 0.017199, 0.097327],
+ [0.025793, 0.019331, 0.105930],
+ [0.029432, 0.021503, 0.114621],
+ [0.033385, 0.023702, 0.123397],
+ [0.037668, 0.025921, 0.132232],
+ [0.042253, 0.028139, 0.141141],
+ [0.046915, 0.030324, 0.150164],
+ [0.051644, 0.032474, 0.159254],
+ [0.056449, 0.034569, 0.168414],
+ [0.061340, 0.036590, 0.177642],
+ [0.066331, 0.038504, 0.186962],
+ [0.071429, 0.040294, 0.196354],
+ [0.076637, 0.041905, 0.205799],
+ [0.081962, 0.043328, 0.215289],
+ [0.087411, 0.044556, 0.224813],
+ [0.092990, 0.045583, 0.234358],
+ [0.098702, 0.046402, 0.243904],
+ [0.104551, 0.047008, 0.253430],
+ [0.110536, 0.047399, 0.262912],
+ [0.116656, 0.047574, 0.272321],
+ [0.122908, 0.047536, 0.281624],
+ [0.129285, 0.047293, 0.290788],
+ [0.135778, 0.046856, 0.299776],
+ [0.142378, 0.046242, 0.308553],
+ [0.149073, 0.045468, 0.317085],
+ [0.155850, 0.044559, 0.325338],
+ [0.162689, 0.043554, 0.333277],
+ [0.169575, 0.042489, 0.340874],
+ [0.176493, 0.041402, 0.348111],
+ [0.183429, 0.040329, 0.354971],
+ [0.190367, 0.039309, 0.361447],
+ [0.197297, 0.038400, 0.367535],
+ [0.204209, 0.037632, 0.373238],
+ [0.211095, 0.037030, 0.378563],
+ [0.217949, 0.036615, 0.383522],
+ [0.224763, 0.036405, 0.388129],
+ [0.231538, 0.036405, 0.392400],
+ [0.238273, 0.036621, 0.396353],
+ [0.244967, 0.037055, 0.400007],
+ [0.251620, 0.037705, 0.403378],
+ [0.258234, 0.038571, 0.406485],
+ [0.264810, 0.039647, 0.409345],
+ [0.271347, 0.040922, 0.411976],
+ [0.277850, 0.042353, 0.414392],
+ [0.284321, 0.043933, 0.416608],
+ [0.290763, 0.045644, 0.418637],
+ [0.297178, 0.047470, 0.420491],
+ [0.303568, 0.049396, 0.422182],
+ [0.309935, 0.051407, 0.423721],
+ [0.316282, 0.053490, 0.425116],
+ [0.322610, 0.055634, 0.426377],
+ [0.328921, 0.057827, 0.427511],
+ [0.335217, 0.060060, 0.428524],
+ [0.341500, 0.062325, 0.429425],
+ [0.347771, 0.064616, 0.430217],
+ [0.354032, 0.066925, 0.430906],
+ [0.360284, 0.069247, 0.431497],
+ [0.366529, 0.071579, 0.431994],
+ [0.372768, 0.073915, 0.432400],
+ [0.379001, 0.076253, 0.432719],
+ [0.385228, 0.078591, 0.432955],
+ [0.391453, 0.080927, 0.433109],
+ [0.397674, 0.083257, 0.433183],
+ [0.403894, 0.085580, 0.433179],
+ [0.410113, 0.087896, 0.433098],
+ [0.416331, 0.090203, 0.432943],
+ [0.422549, 0.092501, 0.432714],
+ [0.428768, 0.094790, 0.432412],
+ [0.434987, 0.097069, 0.432039],
+ [0.441207, 0.099338, 0.431594],
+ [0.447428, 0.101597, 0.431080],
+ [0.453651, 0.103848, 0.430498],
+ [0.459875, 0.106089, 0.429846],
+ [0.466100, 0.108322, 0.429125],
+ [0.472328, 0.110547, 0.428334],
+ [0.478558, 0.112764, 0.427475],
+ [0.484789, 0.114974, 0.426548],
+ [0.491022, 0.117179, 0.425552],
+ [0.497257, 0.119379, 0.424488],
+ [0.503493, 0.121575, 0.423356],
+ [0.509730, 0.123769, 0.422156],
+ [0.515967, 0.125960, 0.420887],
+ [0.522206, 0.128150, 0.419549],
+ [0.528444, 0.130341, 0.418142],
+ [0.534683, 0.132534, 0.416667],
+ [0.540920, 0.134729, 0.415123],
+ [0.547157, 0.136929, 0.413511],
+ [0.553392, 0.139134, 0.411829],
+ [0.559624, 0.141346, 0.410078],
+ [0.565854, 0.143567, 0.408258],
+ [0.572081, 0.145797, 0.406369],
+ [0.578304, 0.148039, 0.404411],
+ [0.584521, 0.150294, 0.402385],
+ [0.590734, 0.152563, 0.400290],
+ [0.596940, 0.154848, 0.398125],
+ [0.603139, 0.157151, 0.395891],
+ [0.609330, 0.159474, 0.393589],
+ [0.615513, 0.161817, 0.391219],
+ [0.621685, 0.164184, 0.388781],
+ [0.627847, 0.166575, 0.386276],
+ [0.633998, 0.168992, 0.383704],
+ [0.640135, 0.171438, 0.381065],
+ [0.646260, 0.173914, 0.378359],
+ [0.652369, 0.176421, 0.375586],
+ [0.658463, 0.178962, 0.372748],
+ [0.664540, 0.181539, 0.369846],
+ [0.670599, 0.184153, 0.366879],
+ [0.676638, 0.186807, 0.363849],
+ [0.682656, 0.189501, 0.360757],
+ [0.688653, 0.192239, 0.357603],
+ [0.694627, 0.195021, 0.354388],
+ [0.700576, 0.197851, 0.351113],
+ [0.706500, 0.200728, 0.347777],
+ [0.712396, 0.203656, 0.344383],
+ [0.718264, 0.206636, 0.340931],
+ [0.724103, 0.209670, 0.337424],
+ [0.729909, 0.212759, 0.333861],
+ [0.735683, 0.215906, 0.330245],
+ [0.741423, 0.219112, 0.326576],
+ [0.747127, 0.222378, 0.322856],
+ [0.752794, 0.225706, 0.319085],
+ [0.758422, 0.229097, 0.315266],
+ [0.764010, 0.232554, 0.311399],
+ [0.769556, 0.236077, 0.307485],
+ [0.775059, 0.239667, 0.303526],
+ [0.780517, 0.243327, 0.299523],
+ [0.785929, 0.247056, 0.295477],
+ [0.791293, 0.250856, 0.291390],
+ [0.796607, 0.254728, 0.287264],
+ [0.801871, 0.258674, 0.283099],
+ [0.807082, 0.262692, 0.278898],
+ [0.812239, 0.266786, 0.274661],
+ [0.817341, 0.270954, 0.270390],
+ [0.822386, 0.275197, 0.266085],
+ [0.827372, 0.279517, 0.261750],
+ [0.832299, 0.283913, 0.257383],
+ [0.837165, 0.288385, 0.252988],
+ [0.841969, 0.292933, 0.248564],
+ [0.846709, 0.297559, 0.244113],
+ [0.851384, 0.302260, 0.239636],
+ [0.855992, 0.307038, 0.235133],
+ [0.860533, 0.311892, 0.230606],
+ [0.865006, 0.316822, 0.226055],
+ [0.869409, 0.321827, 0.221482],
+ [0.873741, 0.326906, 0.216886],
+ [0.878001, 0.332060, 0.212268],
+ [0.882188, 0.337287, 0.207628],
+ [0.886302, 0.342586, 0.202968],
+ [0.890341, 0.347957, 0.198286],
+ [0.894305, 0.353399, 0.193584],
+ [0.898192, 0.358911, 0.188860],
+ [0.902003, 0.364492, 0.184116],
+ [0.905735, 0.370140, 0.179350],
+ [0.909390, 0.375856, 0.174563],
+ [0.912966, 0.381636, 0.169755],
+ [0.916462, 0.387481, 0.164924],
+ [0.919879, 0.393389, 0.160070],
+ [0.923215, 0.399359, 0.155193],
+ [0.926470, 0.405389, 0.150292],
+ [0.929644, 0.411479, 0.145367],
+ [0.932737, 0.417627, 0.140417],
+ [0.935747, 0.423831, 0.135440],
+ [0.938675, 0.430091, 0.130438],
+ [0.941521, 0.436405, 0.125409],
+ [0.944285, 0.442772, 0.120354],
+ [0.946965, 0.449191, 0.115272],
+ [0.949562, 0.455660, 0.110164],
+ [0.952075, 0.462178, 0.105031],
+ [0.954506, 0.468744, 0.099874],
+ [0.956852, 0.475356, 0.094695],
+ [0.959114, 0.482014, 0.089499],
+ [0.961293, 0.488716, 0.084289],
+ [0.963387, 0.495462, 0.079073],
+ [0.965397, 0.502249, 0.073859],
+ [0.967322, 0.509078, 0.068659],
+ [0.969163, 0.515946, 0.063488],
+ [0.970919, 0.522853, 0.058367],
+ [0.972590, 0.529798, 0.053324],
+ [0.974176, 0.536780, 0.048392],
+ [0.975677, 0.543798, 0.043618],
+ [0.977092, 0.550850, 0.039050],
+ [0.978422, 0.557937, 0.034931],
+ [0.979666, 0.565057, 0.031409],
+ [0.980824, 0.572209, 0.028508],
+ [0.981895, 0.579392, 0.026250],
+ [0.982881, 0.586606, 0.024661],
+ [0.983779, 0.593849, 0.023770],
+ [0.984591, 0.601122, 0.023606],
+ [0.985315, 0.608422, 0.024202],
+ [0.985952, 0.615750, 0.025592],
+ [0.986502, 0.623105, 0.027814],
+ [0.986964, 0.630485, 0.030908],
+ [0.987337, 0.637890, 0.034916],
+ [0.987622, 0.645320, 0.039886],
+ [0.987819, 0.652773, 0.045581],
+ [0.987926, 0.660250, 0.051750],
+ [0.987945, 0.667748, 0.058329],
+ [0.987874, 0.675267, 0.065257],
+ [0.987714, 0.682807, 0.072489],
+ [0.987464, 0.690366, 0.079990],
+ [0.987124, 0.697944, 0.087731],
+ [0.986694, 0.705540, 0.095694],
+ [0.986175, 0.713153, 0.103863],
+ [0.985566, 0.720782, 0.112229],
+ [0.984865, 0.728427, 0.120785],
+ [0.984075, 0.736087, 0.129527],
+ [0.983196, 0.743758, 0.138453],
+ [0.982228, 0.751442, 0.147565],
+ [0.981173, 0.759135, 0.156863],
+ [0.980032, 0.766837, 0.166353],
+ [0.978806, 0.774545, 0.176037],
+ [0.977497, 0.782258, 0.185923],
+ [0.976108, 0.789974, 0.196018],
+ [0.974638, 0.797692, 0.206332],
+ [0.973088, 0.805409, 0.216877],
+ [0.971468, 0.813122, 0.227658],
+ [0.969783, 0.820825, 0.238686],
+ [0.968041, 0.828515, 0.249972],
+ [0.966243, 0.836191, 0.261534],
+ [0.964394, 0.843848, 0.273391],
+ [0.962517, 0.851476, 0.285546],
+ [0.960626, 0.859069, 0.298010],
+ [0.958720, 0.866624, 0.310820],
+ [0.956834, 0.874129, 0.323974],
+ [0.954997, 0.881569, 0.337475],
+ [0.953215, 0.888942, 0.351369],
+ [0.951546, 0.896226, 0.365627],
+ [0.950018, 0.903409, 0.380271],
+ [0.948683, 0.910473, 0.395289],
+ [0.947594, 0.917399, 0.410665],
+ [0.946809, 0.924168, 0.426373],
+ [0.946392, 0.930761, 0.442367],
+ [0.946403, 0.937159, 0.458592],
+ [0.946903, 0.943348, 0.474970],
+ [0.947937, 0.949318, 0.491426],
+ [0.949545, 0.955063, 0.507860],
+ [0.951740, 0.960587, 0.524203],
+ [0.954529, 0.965896, 0.540361],
+ [0.957896, 0.971003, 0.556275],
+ [0.961812, 0.975924, 0.571925],
+ [0.966249, 0.980678, 0.587206],
+ [0.971162, 0.985282, 0.602154],
+ [0.976511, 0.989753, 0.616760],
+ [0.982257, 0.994109, 0.631017],
+ [0.988362, 0.998364, 0.644924]]
+
+_plasma_data = [[0.050383, 0.029803, 0.527975],
+ [0.063536, 0.028426, 0.533124],
+ [0.075353, 0.027206, 0.538007],
+ [0.086222, 0.026125, 0.542658],
+ [0.096379, 0.025165, 0.547103],
+ [0.105980, 0.024309, 0.551368],
+ [0.115124, 0.023556, 0.555468],
+ [0.123903, 0.022878, 0.559423],
+ [0.132381, 0.022258, 0.563250],
+ [0.140603, 0.021687, 0.566959],
+ [0.148607, 0.021154, 0.570562],
+ [0.156421, 0.020651, 0.574065],
+ [0.164070, 0.020171, 0.577478],
+ [0.171574, 0.019706, 0.580806],
+ [0.178950, 0.019252, 0.584054],
+ [0.186213, 0.018803, 0.587228],
+ [0.193374, 0.018354, 0.590330],
+ [0.200445, 0.017902, 0.593364],
+ [0.207435, 0.017442, 0.596333],
+ [0.214350, 0.016973, 0.599239],
+ [0.221197, 0.016497, 0.602083],
+ [0.227983, 0.016007, 0.604867],
+ [0.234715, 0.015502, 0.607592],
+ [0.241396, 0.014979, 0.610259],
+ [0.248032, 0.014439, 0.612868],
+ [0.254627, 0.013882, 0.615419],
+ [0.261183, 0.013308, 0.617911],
+ [0.267703, 0.012716, 0.620346],
+ [0.274191, 0.012109, 0.622722],
+ [0.280648, 0.011488, 0.625038],
+ [0.287076, 0.010855, 0.627295],
+ [0.293478, 0.010213, 0.629490],
+ [0.299855, 0.009561, 0.631624],
+ [0.306210, 0.008902, 0.633694],
+ [0.312543, 0.008239, 0.635700],
+ [0.318856, 0.007576, 0.637640],
+ [0.325150, 0.006915, 0.639512],
+ [0.331426, 0.006261, 0.641316],
+ [0.337683, 0.005618, 0.643049],
+ [0.343925, 0.004991, 0.644710],
+ [0.350150, 0.004382, 0.646298],
+ [0.356359, 0.003798, 0.647810],
+ [0.362553, 0.003243, 0.649245],
+ [0.368733, 0.002724, 0.650601],
+ [0.374897, 0.002245, 0.651876],
+ [0.381047, 0.001814, 0.653068],
+ [0.387183, 0.001434, 0.654177],
+ [0.393304, 0.001114, 0.655199],
+ [0.399411, 0.000859, 0.656133],
+ [0.405503, 0.000678, 0.656977],
+ [0.411580, 0.000577, 0.657730],
+ [0.417642, 0.000564, 0.658390],
+ [0.423689, 0.000646, 0.658956],
+ [0.429719, 0.000831, 0.659425],
+ [0.435734, 0.001127, 0.659797],
+ [0.441732, 0.001540, 0.660069],
+ [0.447714, 0.002080, 0.660240],
+ [0.453677, 0.002755, 0.660310],
+ [0.459623, 0.003574, 0.660277],
+ [0.465550, 0.004545, 0.660139],
+ [0.471457, 0.005678, 0.659897],
+ [0.477344, 0.006980, 0.659549],
+ [0.483210, 0.008460, 0.659095],
+ [0.489055, 0.010127, 0.658534],
+ [0.494877, 0.011990, 0.657865],
+ [0.500678, 0.014055, 0.657088],
+ [0.506454, 0.016333, 0.656202],
+ [0.512206, 0.018833, 0.655209],
+ [0.517933, 0.021563, 0.654109],
+ [0.523633, 0.024532, 0.652901],
+ [0.529306, 0.027747, 0.651586],
+ [0.534952, 0.031217, 0.650165],
+ [0.540570, 0.034950, 0.648640],
+ [0.546157, 0.038954, 0.647010],
+ [0.551715, 0.043136, 0.645277],
+ [0.557243, 0.047331, 0.643443],
+ [0.562738, 0.051545, 0.641509],
+ [0.568201, 0.055778, 0.639477],
+ [0.573632, 0.060028, 0.637349],
+ [0.579029, 0.064296, 0.635126],
+ [0.584391, 0.068579, 0.632812],
+ [0.589719, 0.072878, 0.630408],
+ [0.595011, 0.077190, 0.627917],
+ [0.600266, 0.081516, 0.625342],
+ [0.605485, 0.085854, 0.622686],
+ [0.610667, 0.090204, 0.619951],
+ [0.615812, 0.094564, 0.617140],
+ [0.620919, 0.098934, 0.614257],
+ [0.625987, 0.103312, 0.611305],
+ [0.631017, 0.107699, 0.608287],
+ [0.636008, 0.112092, 0.605205],
+ [0.640959, 0.116492, 0.602065],
+ [0.645872, 0.120898, 0.598867],
+ [0.650746, 0.125309, 0.595617],
+ [0.655580, 0.129725, 0.592317],
+ [0.660374, 0.134144, 0.588971],
+ [0.665129, 0.138566, 0.585582],
+ [0.669845, 0.142992, 0.582154],
+ [0.674522, 0.147419, 0.578688],
+ [0.679160, 0.151848, 0.575189],
+ [0.683758, 0.156278, 0.571660],
+ [0.688318, 0.160709, 0.568103],
+ [0.692840, 0.165141, 0.564522],
+ [0.697324, 0.169573, 0.560919],
+ [0.701769, 0.174005, 0.557296],
+ [0.706178, 0.178437, 0.553657],
+ [0.710549, 0.182868, 0.550004],
+ [0.714883, 0.187299, 0.546338],
+ [0.719181, 0.191729, 0.542663],
+ [0.723444, 0.196158, 0.538981],
+ [0.727670, 0.200586, 0.535293],
+ [0.731862, 0.205013, 0.531601],
+ [0.736019, 0.209439, 0.527908],
+ [0.740143, 0.213864, 0.524216],
+ [0.744232, 0.218288, 0.520524],
+ [0.748289, 0.222711, 0.516834],
+ [0.752312, 0.227133, 0.513149],
+ [0.756304, 0.231555, 0.509468],
+ [0.760264, 0.235976, 0.505794],
+ [0.764193, 0.240396, 0.502126],
+ [0.768090, 0.244817, 0.498465],
+ [0.771958, 0.249237, 0.494813],
+ [0.775796, 0.253658, 0.491171],
+ [0.779604, 0.258078, 0.487539],
+ [0.783383, 0.262500, 0.483918],
+ [0.787133, 0.266922, 0.480307],
+ [0.790855, 0.271345, 0.476706],
+ [0.794549, 0.275770, 0.473117],
+ [0.798216, 0.280197, 0.469538],
+ [0.801855, 0.284626, 0.465971],
+ [0.805467, 0.289057, 0.462415],
+ [0.809052, 0.293491, 0.458870],
+ [0.812612, 0.297928, 0.455338],
+ [0.816144, 0.302368, 0.451816],
+ [0.819651, 0.306812, 0.448306],
+ [0.823132, 0.311261, 0.444806],
+ [0.826588, 0.315714, 0.441316],
+ [0.830018, 0.320172, 0.437836],
+ [0.833422, 0.324635, 0.434366],
+ [0.836801, 0.329105, 0.430905],
+ [0.840155, 0.333580, 0.427455],
+ [0.843484, 0.338062, 0.424013],
+ [0.846788, 0.342551, 0.420579],
+ [0.850066, 0.347048, 0.417153],
+ [0.853319, 0.351553, 0.413734],
+ [0.856547, 0.356066, 0.410322],
+ [0.859750, 0.360588, 0.406917],
+ [0.862927, 0.365119, 0.403519],
+ [0.866078, 0.369660, 0.400126],
+ [0.869203, 0.374212, 0.396738],
+ [0.872303, 0.378774, 0.393355],
+ [0.875376, 0.383347, 0.389976],
+ [0.878423, 0.387932, 0.386600],
+ [0.881443, 0.392529, 0.383229],
+ [0.884436, 0.397139, 0.379860],
+ [0.887402, 0.401762, 0.376494],
+ [0.890340, 0.406398, 0.373130],
+ [0.893250, 0.411048, 0.369768],
+ [0.896131, 0.415712, 0.366407],
+ [0.898984, 0.420392, 0.363047],
+ [0.901807, 0.425087, 0.359688],
+ [0.904601, 0.429797, 0.356329],
+ [0.907365, 0.434524, 0.352970],
+ [0.910098, 0.439268, 0.349610],
+ [0.912800, 0.444029, 0.346251],
+ [0.915471, 0.448807, 0.342890],
+ [0.918109, 0.453603, 0.339529],
+ [0.920714, 0.458417, 0.336166],
+ [0.923287, 0.463251, 0.332801],
+ [0.925825, 0.468103, 0.329435],
+ [0.928329, 0.472975, 0.326067],
+ [0.930798, 0.477867, 0.322697],
+ [0.933232, 0.482780, 0.319325],
+ [0.935630, 0.487712, 0.315952],
+ [0.937990, 0.492667, 0.312575],
+ [0.940313, 0.497642, 0.309197],
+ [0.942598, 0.502639, 0.305816],
+ [0.944844, 0.507658, 0.302433],
+ [0.947051, 0.512699, 0.299049],
+ [0.949217, 0.517763, 0.295662],
+ [0.951344, 0.522850, 0.292275],
+ [0.953428, 0.527960, 0.288883],
+ [0.955470, 0.533093, 0.285490],
+ [0.957469, 0.538250, 0.282096],
+ [0.959424, 0.543431, 0.278701],
+ [0.961336, 0.548636, 0.275305],
+ [0.963203, 0.553865, 0.271909],
+ [0.965024, 0.559118, 0.268513],
+ [0.966798, 0.564396, 0.265118],
+ [0.968526, 0.569700, 0.261721],
+ [0.970205, 0.575028, 0.258325],
+ [0.971835, 0.580382, 0.254931],
+ [0.973416, 0.585761, 0.251540],
+ [0.974947, 0.591165, 0.248151],
+ [0.976428, 0.596595, 0.244767],
+ [0.977856, 0.602051, 0.241387],
+ [0.979233, 0.607532, 0.238013],
+ [0.980556, 0.613039, 0.234646],
+ [0.981826, 0.618572, 0.231287],
+ [0.983041, 0.624131, 0.227937],
+ [0.984199, 0.629718, 0.224595],
+ [0.985301, 0.635330, 0.221265],
+ [0.986345, 0.640969, 0.217948],
+ [0.987332, 0.646633, 0.214648],
+ [0.988260, 0.652325, 0.211364],
+ [0.989128, 0.658043, 0.208100],
+ [0.989935, 0.663787, 0.204859],
+ [0.990681, 0.669558, 0.201642],
+ [0.991365, 0.675355, 0.198453],
+ [0.991985, 0.681179, 0.195295],
+ [0.992541, 0.687030, 0.192170],
+ [0.993032, 0.692907, 0.189084],
+ [0.993456, 0.698810, 0.186041],
+ [0.993814, 0.704741, 0.183043],
+ [0.994103, 0.710698, 0.180097],
+ [0.994324, 0.716681, 0.177208],
+ [0.994474, 0.722691, 0.174381],
+ [0.994553, 0.728728, 0.171622],
+ [0.994561, 0.734791, 0.168938],
+ [0.994495, 0.740880, 0.166335],
+ [0.994355, 0.746995, 0.163821],
+ [0.994141, 0.753137, 0.161404],
+ [0.993851, 0.759304, 0.159092],
+ [0.993482, 0.765499, 0.156891],
+ [0.993033, 0.771720, 0.154808],
+ [0.992505, 0.777967, 0.152855],
+ [0.991897, 0.784239, 0.151042],
+ [0.991209, 0.790537, 0.149377],
+ [0.990439, 0.796859, 0.147870],
+ [0.989587, 0.803205, 0.146529],
+ [0.988648, 0.809579, 0.145357],
+ [0.987621, 0.815978, 0.144363],
+ [0.986509, 0.822401, 0.143557],
+ [0.985314, 0.828846, 0.142945],
+ [0.984031, 0.835315, 0.142528],
+ [0.982653, 0.841812, 0.142303],
+ [0.981190, 0.848329, 0.142279],
+ [0.979644, 0.854866, 0.142453],
+ [0.977995, 0.861432, 0.142808],
+ [0.976265, 0.868016, 0.143351],
+ [0.974443, 0.874622, 0.144061],
+ [0.972530, 0.881250, 0.144923],
+ [0.970533, 0.887896, 0.145919],
+ [0.968443, 0.894564, 0.147014],
+ [0.966271, 0.901249, 0.148180],
+ [0.964021, 0.907950, 0.149370],
+ [0.961681, 0.914672, 0.150520],
+ [0.959276, 0.921407, 0.151566],
+ [0.956808, 0.928152, 0.152409],
+ [0.954287, 0.934908, 0.152921],
+ [0.951726, 0.941671, 0.152925],
+ [0.949151, 0.948435, 0.152178],
+ [0.946602, 0.955190, 0.150328],
+ [0.944152, 0.961916, 0.146861],
+ [0.941896, 0.968590, 0.140956],
+ [0.940015, 0.975158, 0.131326]]
+
+_viridis_data = [[0.267004, 0.004874, 0.329415],
+ [0.268510, 0.009605, 0.335427],
+ [0.269944, 0.014625, 0.341379],
+ [0.271305, 0.019942, 0.347269],
+ [0.272594, 0.025563, 0.353093],
+ [0.273809, 0.031497, 0.358853],
+ [0.274952, 0.037752, 0.364543],
+ [0.276022, 0.044167, 0.370164],
+ [0.277018, 0.050344, 0.375715],
+ [0.277941, 0.056324, 0.381191],
+ [0.278791, 0.062145, 0.386592],
+ [0.279566, 0.067836, 0.391917],
+ [0.280267, 0.073417, 0.397163],
+ [0.280894, 0.078907, 0.402329],
+ [0.281446, 0.084320, 0.407414],
+ [0.281924, 0.089666, 0.412415],
+ [0.282327, 0.094955, 0.417331],
+ [0.282656, 0.100196, 0.422160],
+ [0.282910, 0.105393, 0.426902],
+ [0.283091, 0.110553, 0.431554],
+ [0.283197, 0.115680, 0.436115],
+ [0.283229, 0.120777, 0.440584],
+ [0.283187, 0.125848, 0.444960],
+ [0.283072, 0.130895, 0.449241],
+ [0.282884, 0.135920, 0.453427],
+ [0.282623, 0.140926, 0.457517],
+ [0.282290, 0.145912, 0.461510],
+ [0.281887, 0.150881, 0.465405],
+ [0.281412, 0.155834, 0.469201],
+ [0.280868, 0.160771, 0.472899],
+ [0.280255, 0.165693, 0.476498],
+ [0.279574, 0.170599, 0.479997],
+ [0.278826, 0.175490, 0.483397],
+ [0.278012, 0.180367, 0.486697],
+ [0.277134, 0.185228, 0.489898],
+ [0.276194, 0.190074, 0.493001],
+ [0.275191, 0.194905, 0.496005],
+ [0.274128, 0.199721, 0.498911],
+ [0.273006, 0.204520, 0.501721],
+ [0.271828, 0.209303, 0.504434],
+ [0.270595, 0.214069, 0.507052],
+ [0.269308, 0.218818, 0.509577],
+ [0.267968, 0.223549, 0.512008],
+ [0.266580, 0.228262, 0.514349],
+ [0.265145, 0.232956, 0.516599],
+ [0.263663, 0.237631, 0.518762],
+ [0.262138, 0.242286, 0.520837],
+ [0.260571, 0.246922, 0.522828],
+ [0.258965, 0.251537, 0.524736],
+ [0.257322, 0.256130, 0.526563],
+ [0.255645, 0.260703, 0.528312],
+ [0.253935, 0.265254, 0.529983],
+ [0.252194, 0.269783, 0.531579],
+ [0.250425, 0.274290, 0.533103],
+ [0.248629, 0.278775, 0.534556],
+ [0.246811, 0.283237, 0.535941],
+ [0.244972, 0.287675, 0.537260],
+ [0.243113, 0.292092, 0.538516],
+ [0.241237, 0.296485, 0.539709],
+ [0.239346, 0.300855, 0.540844],
+ [0.237441, 0.305202, 0.541921],
+ [0.235526, 0.309527, 0.542944],
+ [0.233603, 0.313828, 0.543914],
+ [0.231674, 0.318106, 0.544834],
+ [0.229739, 0.322361, 0.545706],
+ [0.227802, 0.326594, 0.546532],
+ [0.225863, 0.330805, 0.547314],
+ [0.223925, 0.334994, 0.548053],
+ [0.221989, 0.339161, 0.548752],
+ [0.220057, 0.343307, 0.549413],
+ [0.218130, 0.347432, 0.550038],
+ [0.216210, 0.351535, 0.550627],
+ [0.214298, 0.355619, 0.551184],
+ [0.212395, 0.359683, 0.551710],
+ [0.210503, 0.363727, 0.552206],
+ [0.208623, 0.367752, 0.552675],
+ [0.206756, 0.371758, 0.553117],
+ [0.204903, 0.375746, 0.553533],
+ [0.203063, 0.379716, 0.553925],
+ [0.201239, 0.383670, 0.554294],
+ [0.199430, 0.387607, 0.554642],
+ [0.197636, 0.391528, 0.554969],
+ [0.195860, 0.395433, 0.555276],
+ [0.194100, 0.399323, 0.555565],
+ [0.192357, 0.403199, 0.555836],
+ [0.190631, 0.407061, 0.556089],
+ [0.188923, 0.410910, 0.556326],
+ [0.187231, 0.414746, 0.556547],
+ [0.185556, 0.418570, 0.556753],
+ [0.183898, 0.422383, 0.556944],
+ [0.182256, 0.426184, 0.557120],
+ [0.180629, 0.429975, 0.557282],
+ [0.179019, 0.433756, 0.557430],
+ [0.177423, 0.437527, 0.557565],
+ [0.175841, 0.441290, 0.557685],
+ [0.174274, 0.445044, 0.557792],
+ [0.172719, 0.448791, 0.557885],
+ [0.171176, 0.452530, 0.557965],
+ [0.169646, 0.456262, 0.558030],
+ [0.168126, 0.459988, 0.558082],
+ [0.166617, 0.463708, 0.558119],
+ [0.165117, 0.467423, 0.558141],
+ [0.163625, 0.471133, 0.558148],
+ [0.162142, 0.474838, 0.558140],
+ [0.160665, 0.478540, 0.558115],
+ [0.159194, 0.482237, 0.558073],
+ [0.157729, 0.485932, 0.558013],
+ [0.156270, 0.489624, 0.557936],
+ [0.154815, 0.493313, 0.557840],
+ [0.153364, 0.497000, 0.557724],
+ [0.151918, 0.500685, 0.557587],
+ [0.150476, 0.504369, 0.557430],
+ [0.149039, 0.508051, 0.557250],
+ [0.147607, 0.511733, 0.557049],
+ [0.146180, 0.515413, 0.556823],
+ [0.144759, 0.519093, 0.556572],
+ [0.143343, 0.522773, 0.556295],
+ [0.141935, 0.526453, 0.555991],
+ [0.140536, 0.530132, 0.555659],
+ [0.139147, 0.533812, 0.555298],
+ [0.137770, 0.537492, 0.554906],
+ [0.136408, 0.541173, 0.554483],
+ [0.135066, 0.544853, 0.554029],
+ [0.133743, 0.548535, 0.553541],
+ [0.132444, 0.552216, 0.553018],
+ [0.131172, 0.555899, 0.552459],
+ [0.129933, 0.559582, 0.551864],
+ [0.128729, 0.563265, 0.551229],
+ [0.127568, 0.566949, 0.550556],
+ [0.126453, 0.570633, 0.549841],
+ [0.125394, 0.574318, 0.549086],
+ [0.124395, 0.578002, 0.548287],
+ [0.123463, 0.581687, 0.547445],
+ [0.122606, 0.585371, 0.546557],
+ [0.121831, 0.589055, 0.545623],
+ [0.121148, 0.592739, 0.544641],
+ [0.120565, 0.596422, 0.543611],
+ [0.120092, 0.600104, 0.542530],
+ [0.119738, 0.603785, 0.541400],
+ [0.119512, 0.607464, 0.540218],
+ [0.119423, 0.611141, 0.538982],
+ [0.119483, 0.614817, 0.537692],
+ [0.119699, 0.618490, 0.536347],
+ [0.120081, 0.622161, 0.534946],
+ [0.120638, 0.625828, 0.533488],
+ [0.121380, 0.629492, 0.531973],
+ [0.122312, 0.633153, 0.530398],
+ [0.123444, 0.636809, 0.528763],
+ [0.124780, 0.640461, 0.527068],
+ [0.126326, 0.644107, 0.525311],
+ [0.128087, 0.647749, 0.523491],
+ [0.130067, 0.651384, 0.521608],
+ [0.132268, 0.655014, 0.519661],
+ [0.134692, 0.658636, 0.517649],
+ [0.137339, 0.662252, 0.515571],
+ [0.140210, 0.665859, 0.513427],
+ [0.143303, 0.669459, 0.511215],
+ [0.146616, 0.673050, 0.508936],
+ [0.150148, 0.676631, 0.506589],
+ [0.153894, 0.680203, 0.504172],
+ [0.157851, 0.683765, 0.501686],
+ [0.162016, 0.687316, 0.499129],
+ [0.166383, 0.690856, 0.496502],
+ [0.170948, 0.694384, 0.493803],
+ [0.175707, 0.697900, 0.491033],
+ [0.180653, 0.701402, 0.488189],
+ [0.185783, 0.704891, 0.485273],
+ [0.191090, 0.708366, 0.482284],
+ [0.196571, 0.711827, 0.479221],
+ [0.202219, 0.715272, 0.476084],
+ [0.208030, 0.718701, 0.472873],
+ [0.214000, 0.722114, 0.469588],
+ [0.220124, 0.725509, 0.466226],
+ [0.226397, 0.728888, 0.462789],
+ [0.232815, 0.732247, 0.459277],
+ [0.239374, 0.735588, 0.455688],
+ [0.246070, 0.738910, 0.452024],
+ [0.252899, 0.742211, 0.448284],
+ [0.259857, 0.745492, 0.444467],
+ [0.266941, 0.748751, 0.440573],
+ [0.274149, 0.751988, 0.436601],
+ [0.281477, 0.755203, 0.432552],
+ [0.288921, 0.758394, 0.428426],
+ [0.296479, 0.761561, 0.424223],
+ [0.304148, 0.764704, 0.419943],
+ [0.311925, 0.767822, 0.415586],
+ [0.319809, 0.770914, 0.411152],
+ [0.327796, 0.773980, 0.406640],
+ [0.335885, 0.777018, 0.402049],
+ [0.344074, 0.780029, 0.397381],
+ [0.352360, 0.783011, 0.392636],
+ [0.360741, 0.785964, 0.387814],
+ [0.369214, 0.788888, 0.382914],
+ [0.377779, 0.791781, 0.377939],
+ [0.386433, 0.794644, 0.372886],
+ [0.395174, 0.797475, 0.367757],
+ [0.404001, 0.800275, 0.362552],
+ [0.412913, 0.803041, 0.357269],
+ [0.421908, 0.805774, 0.351910],
+ [0.430983, 0.808473, 0.346476],
+ [0.440137, 0.811138, 0.340967],
+ [0.449368, 0.813768, 0.335384],
+ [0.458674, 0.816363, 0.329727],
+ [0.468053, 0.818921, 0.323998],
+ [0.477504, 0.821444, 0.318195],
+ [0.487026, 0.823929, 0.312321],
+ [0.496615, 0.826376, 0.306377],
+ [0.506271, 0.828786, 0.300362],
+ [0.515992, 0.831158, 0.294279],
+ [0.525776, 0.833491, 0.288127],
+ [0.535621, 0.835785, 0.281908],
+ [0.545524, 0.838039, 0.275626],
+ [0.555484, 0.840254, 0.269281],
+ [0.565498, 0.842430, 0.262877],
+ [0.575563, 0.844566, 0.256415],
+ [0.585678, 0.846661, 0.249897],
+ [0.595839, 0.848717, 0.243329],
+ [0.606045, 0.850733, 0.236712],
+ [0.616293, 0.852709, 0.230052],
+ [0.626579, 0.854645, 0.223353],
+ [0.636902, 0.856542, 0.216620],
+ [0.647257, 0.858400, 0.209861],
+ [0.657642, 0.860219, 0.203082],
+ [0.668054, 0.861999, 0.196293],
+ [0.678489, 0.863742, 0.189503],
+ [0.688944, 0.865448, 0.182725],
+ [0.699415, 0.867117, 0.175971],
+ [0.709898, 0.868751, 0.169257],
+ [0.720391, 0.870350, 0.162603],
+ [0.730889, 0.871916, 0.156029],
+ [0.741388, 0.873449, 0.149561],
+ [0.751884, 0.874951, 0.143228],
+ [0.762373, 0.876424, 0.137064],
+ [0.772852, 0.877868, 0.131109],
+ [0.783315, 0.879285, 0.125405],
+ [0.793760, 0.880678, 0.120005],
+ [0.804182, 0.882046, 0.114965],
+ [0.814576, 0.883393, 0.110347],
+ [0.824940, 0.884720, 0.106217],
+ [0.835270, 0.886029, 0.102646],
+ [0.845561, 0.887322, 0.099702],
+ [0.855810, 0.888601, 0.097452],
+ [0.866013, 0.889868, 0.095953],
+ [0.876168, 0.891125, 0.095250],
+ [0.886271, 0.892374, 0.095374],
+ [0.896320, 0.893616, 0.096335],
+ [0.906311, 0.894855, 0.098125],
+ [0.916242, 0.896091, 0.100717],
+ [0.926106, 0.897330, 0.104071],
+ [0.935904, 0.898570, 0.108131],
+ [0.945636, 0.899815, 0.112838],
+ [0.955300, 0.901065, 0.118128],
+ [0.964894, 0.902323, 0.123941],
+ [0.974417, 0.903590, 0.130215],
+ [0.983868, 0.904867, 0.136897],
+ [0.993248, 0.906157, 0.143936]]
+
+_cividis_data = [[0.000000, 0.135112, 0.304751],
+ [0.000000, 0.138068, 0.311105],
+ [0.000000, 0.141013, 0.317579],
+ [0.000000, 0.143951, 0.323982],
+ [0.000000, 0.146877, 0.330479],
+ [0.000000, 0.149791, 0.337065],
+ [0.000000, 0.152673, 0.343704],
+ [0.000000, 0.155377, 0.350500],
+ [0.000000, 0.157932, 0.357521],
+ [0.000000, 0.160495, 0.364534],
+ [0.000000, 0.163058, 0.371608],
+ [0.000000, 0.165621, 0.378769],
+ [0.000000, 0.168204, 0.385902],
+ [0.000000, 0.170800, 0.393100],
+ [0.000000, 0.173420, 0.400353],
+ [0.000000, 0.176082, 0.407577],
+ [0.000000, 0.178802, 0.414764],
+ [0.000000, 0.181610, 0.421859],
+ [0.000000, 0.184550, 0.428802],
+ [0.000000, 0.186915, 0.435532],
+ [0.000000, 0.188769, 0.439563],
+ [0.000000, 0.190950, 0.441085],
+ [0.000000, 0.193366, 0.441561],
+ [0.003602, 0.195911, 0.441564],
+ [0.017852, 0.198528, 0.441248],
+ [0.032110, 0.201199, 0.440785],
+ [0.046205, 0.203903, 0.440196],
+ [0.058378, 0.206629, 0.439531],
+ [0.068968, 0.209372, 0.438863],
+ [0.078624, 0.212122, 0.438105],
+ [0.087465, 0.214879, 0.437342],
+ [0.095645, 0.217643, 0.436593],
+ [0.103401, 0.220406, 0.435790],
+ [0.110658, 0.223170, 0.435067],
+ [0.117612, 0.225935, 0.434308],
+ [0.124291, 0.228697, 0.433547],
+ [0.130669, 0.231458, 0.432840],
+ [0.136830, 0.234216, 0.432148],
+ [0.142852, 0.236972, 0.431404],
+ [0.148638, 0.239724, 0.430752],
+ [0.154261, 0.242475, 0.430120],
+ [0.159733, 0.245221, 0.429528],
+ [0.165113, 0.247965, 0.428908],
+ [0.170362, 0.250707, 0.428325],
+ [0.175490, 0.253444, 0.427790],
+ [0.180503, 0.256180, 0.427299],
+ [0.185453, 0.258914, 0.426788],
+ [0.190303, 0.261644, 0.426329],
+ [0.195057, 0.264372, 0.425924],
+ [0.199764, 0.267099, 0.425497],
+ [0.204385, 0.269823, 0.425126],
+ [0.208926, 0.272546, 0.424809],
+ [0.213431, 0.275266, 0.424480],
+ [0.217863, 0.277985, 0.424206],
+ [0.222264, 0.280702, 0.423914],
+ [0.226598, 0.283419, 0.423678],
+ [0.230871, 0.286134, 0.423498],
+ [0.235120, 0.288848, 0.423304],
+ [0.239312, 0.291562, 0.423167],
+ [0.243485, 0.294274, 0.423014],
+ [0.247605, 0.296986, 0.422917],
+ [0.251675, 0.299698, 0.422873],
+ [0.255731, 0.302409, 0.422814],
+ [0.259740, 0.305120, 0.422810],
+ [0.263738, 0.307831, 0.422789],
+ [0.267693, 0.310542, 0.422821],
+ [0.271639, 0.313253, 0.422837],
+ [0.275513, 0.315965, 0.422979],
+ [0.279411, 0.318677, 0.423031],
+ [0.283240, 0.321390, 0.423211],
+ [0.287065, 0.324103, 0.423373],
+ [0.290884, 0.326816, 0.423517],
+ [0.294669, 0.329531, 0.423716],
+ [0.298421, 0.332247, 0.423973],
+ [0.302169, 0.334963, 0.424213],
+ [0.305886, 0.337681, 0.424512],
+ [0.309601, 0.340399, 0.424790],
+ [0.313287, 0.343120, 0.425120],
+ [0.316941, 0.345842, 0.425512],
+ [0.320595, 0.348565, 0.425889],
+ [0.324250, 0.351289, 0.426250],
+ [0.327875, 0.354016, 0.426670],
+ [0.331474, 0.356744, 0.427144],
+ [0.335073, 0.359474, 0.427605],
+ [0.338673, 0.362206, 0.428053],
+ [0.342246, 0.364939, 0.428559],
+ [0.345793, 0.367676, 0.429127],
+ [0.349341, 0.370414, 0.429685],
+ [0.352892, 0.373153, 0.430226],
+ [0.356418, 0.375896, 0.430823],
+ [0.359916, 0.378641, 0.431501],
+ [0.363446, 0.381388, 0.432075],
+ [0.366923, 0.384139, 0.432796],
+ [0.370430, 0.386890, 0.433428],
+ [0.373884, 0.389646, 0.434209],
+ [0.377371, 0.392404, 0.434890],
+ [0.380830, 0.395164, 0.435653],
+ [0.384268, 0.397928, 0.436475],
+ [0.387705, 0.400694, 0.437305],
+ [0.391151, 0.403464, 0.438096],
+ [0.394568, 0.406236, 0.438986],
+ [0.397991, 0.409011, 0.439848],
+ [0.401418, 0.411790, 0.440708],
+ [0.404820, 0.414572, 0.441642],
+ [0.408226, 0.417357, 0.442570],
+ [0.411607, 0.420145, 0.443577],
+ [0.414992, 0.422937, 0.444578],
+ [0.418383, 0.425733, 0.445560],
+ [0.421748, 0.428531, 0.446640],
+ [0.425120, 0.431334, 0.447692],
+ [0.428462, 0.434140, 0.448864],
+ [0.431817, 0.436950, 0.449982],
+ [0.435168, 0.439763, 0.451134],
+ [0.438504, 0.442580, 0.452341],
+ [0.441810, 0.445402, 0.453659],
+ [0.445148, 0.448226, 0.454885],
+ [0.448447, 0.451053, 0.456264],
+ [0.451759, 0.453887, 0.457582],
+ [0.455072, 0.456718, 0.458976],
+ [0.458366, 0.459552, 0.460457],
+ [0.461616, 0.462405, 0.461969],
+ [0.464947, 0.465241, 0.463395],
+ [0.468254, 0.468083, 0.464908],
+ [0.471501, 0.470960, 0.466357],
+ [0.474812, 0.473832, 0.467681],
+ [0.478186, 0.476699, 0.468845],
+ [0.481622, 0.479573, 0.469767],
+ [0.485141, 0.482451, 0.470384],
+ [0.488697, 0.485318, 0.471008],
+ [0.492278, 0.488198, 0.471453],
+ [0.495913, 0.491076, 0.471751],
+ [0.499552, 0.493960, 0.472032],
+ [0.503185, 0.496851, 0.472305],
+ [0.506866, 0.499743, 0.472432],
+ [0.510540, 0.502643, 0.472550],
+ [0.514226, 0.505546, 0.472640],
+ [0.517920, 0.508454, 0.472707],
+ [0.521643, 0.511367, 0.472639],
+ [0.525348, 0.514285, 0.472660],
+ [0.529086, 0.517207, 0.472543],
+ [0.532829, 0.520135, 0.472401],
+ [0.536553, 0.523067, 0.472352],
+ [0.540307, 0.526005, 0.472163],
+ [0.544069, 0.528948, 0.471947],
+ [0.547840, 0.531895, 0.471704],
+ [0.551612, 0.534849, 0.471439],
+ [0.555393, 0.537807, 0.471147],
+ [0.559181, 0.540771, 0.470829],
+ [0.562972, 0.543741, 0.470488],
+ [0.566802, 0.546715, 0.469988],
+ [0.570607, 0.549695, 0.469593],
+ [0.574417, 0.552682, 0.469172],
+ [0.578236, 0.555673, 0.468724],
+ [0.582087, 0.558670, 0.468118],
+ [0.585916, 0.561674, 0.467618],
+ [0.589753, 0.564682, 0.467090],
+ [0.593622, 0.567697, 0.466401],
+ [0.597469, 0.570718, 0.465821],
+ [0.601354, 0.573743, 0.465074],
+ [0.605211, 0.576777, 0.464441],
+ [0.609105, 0.579816, 0.463638],
+ [0.612977, 0.582861, 0.462950],
+ [0.616852, 0.585913, 0.462237],
+ [0.620765, 0.588970, 0.461351],
+ [0.624654, 0.592034, 0.460583],
+ [0.628576, 0.595104, 0.459641],
+ [0.632506, 0.598180, 0.458668],
+ [0.636412, 0.601264, 0.457818],
+ [0.640352, 0.604354, 0.456791],
+ [0.644270, 0.607450, 0.455886],
+ [0.648222, 0.610553, 0.454801],
+ [0.652178, 0.613664, 0.453689],
+ [0.656114, 0.616780, 0.452702],
+ [0.660082, 0.619904, 0.451534],
+ [0.664055, 0.623034, 0.450338],
+ [0.668008, 0.626171, 0.449270],
+ [0.671991, 0.629316, 0.448018],
+ [0.675981, 0.632468, 0.446736],
+ [0.679979, 0.635626, 0.445424],
+ [0.683950, 0.638793, 0.444251],
+ [0.687957, 0.641966, 0.442886],
+ [0.691971, 0.645145, 0.441491],
+ [0.695985, 0.648334, 0.440072],
+ [0.700008, 0.651529, 0.438624],
+ [0.704037, 0.654731, 0.437147],
+ [0.708067, 0.657942, 0.435647],
+ [0.712105, 0.661160, 0.434117],
+ [0.716177, 0.664384, 0.432386],
+ [0.720222, 0.667618, 0.430805],
+ [0.724274, 0.670859, 0.429194],
+ [0.728334, 0.674107, 0.427554],
+ [0.732422, 0.677364, 0.425717],
+ [0.736488, 0.680629, 0.424028],
+ [0.740589, 0.683900, 0.422131],
+ [0.744664, 0.687181, 0.420393],
+ [0.748772, 0.690470, 0.418448],
+ [0.752886, 0.693766, 0.416472],
+ [0.756975, 0.697071, 0.414659],
+ [0.761096, 0.700384, 0.412638],
+ [0.765223, 0.703705, 0.410587],
+ [0.769353, 0.707035, 0.408516],
+ [0.773486, 0.710373, 0.406422],
+ [0.777651, 0.713719, 0.404112],
+ [0.781795, 0.717074, 0.401966],
+ [0.785965, 0.720438, 0.399613],
+ [0.790116, 0.723810, 0.397423],
+ [0.794298, 0.727190, 0.395016],
+ [0.798480, 0.730580, 0.392597],
+ [0.802667, 0.733978, 0.390153],
+ [0.806859, 0.737385, 0.387684],
+ [0.811054, 0.740801, 0.385198],
+ [0.815274, 0.744226, 0.382504],
+ [0.819499, 0.747659, 0.379785],
+ [0.823729, 0.751101, 0.377043],
+ [0.827959, 0.754553, 0.374292],
+ [0.832192, 0.758014, 0.371529],
+ [0.836429, 0.761483, 0.368747],
+ [0.840693, 0.764962, 0.365746],
+ [0.844957, 0.768450, 0.362741],
+ [0.849223, 0.771947, 0.359729],
+ [0.853515, 0.775454, 0.356500],
+ [0.857809, 0.778969, 0.353259],
+ [0.862105, 0.782494, 0.350011],
+ [0.866421, 0.786028, 0.346571],
+ [0.870717, 0.789572, 0.343333],
+ [0.875057, 0.793125, 0.339685],
+ [0.879378, 0.796687, 0.336241],
+ [0.883720, 0.800258, 0.332599],
+ [0.888081, 0.803839, 0.328770],
+ [0.892440, 0.807430, 0.324968],
+ [0.896818, 0.811030, 0.320982],
+ [0.901195, 0.814639, 0.317021],
+ [0.905589, 0.818257, 0.312889],
+ [0.910000, 0.821885, 0.308594],
+ [0.914407, 0.825522, 0.304348],
+ [0.918828, 0.829168, 0.299960],
+ [0.923279, 0.832822, 0.295244],
+ [0.927724, 0.836486, 0.290611],
+ [0.932180, 0.840159, 0.285880],
+ [0.936660, 0.843841, 0.280876],
+ [0.941147, 0.847530, 0.275815],
+ [0.945654, 0.851228, 0.270532],
+ [0.950178, 0.854933, 0.265085],
+ [0.954725, 0.858646, 0.259365],
+ [0.959284, 0.862365, 0.253563],
+ [0.963872, 0.866089, 0.247445],
+ [0.968469, 0.869819, 0.241310],
+ [0.973114, 0.873550, 0.234677],
+ [0.977780, 0.877281, 0.227954],
+ [0.982497, 0.881008, 0.220878],
+ [0.987293, 0.884718, 0.213336],
+ [0.992218, 0.888385, 0.205468],
+ [0.994847, 0.892954, 0.203445],
+ [0.995249, 0.898384, 0.207561],
+ [0.995503, 0.903866, 0.212370],
+ [0.995737, 0.909344, 0.217772]]
+
+_twilight_data = [
+ [0.88575015840754434, 0.85000924943067835, 0.8879736506427196],
+ [0.88378520195539056, 0.85072940540310626, 0.88723222096949894],
+ [0.88172231059285788, 0.85127594077653468, 0.88638056925514819],
+ [0.8795410528270573, 0.85165675407495722, 0.8854143767924102],
+ [0.87724880858965482, 0.85187028338870274, 0.88434120381311432],
+ [0.87485347508575972, 0.85191526123023187, 0.88316926967613829],
+ [0.87233134085124076, 0.85180165478080894, 0.88189704355001619],
+ [0.86970474853509816, 0.85152403004797894, 0.88053883390003362],
+ [0.86696015505333579, 0.8510896085314068, 0.87909766977173343],
+ [0.86408985081463996, 0.85050391167507788, 0.87757925784892632],
+ [0.86110245436899846, 0.84976754857001258, 0.87599242923439569],
+ [0.85798259245670372, 0.84888934810281835, 0.87434038553446281],
+ [0.85472593189256985, 0.84787488124672816, 0.8726282980930582],
+ [0.85133714570857189, 0.84672735796116472, 0.87086081657350445],
+ [0.84780710702577922, 0.8454546229209523, 0.86904036783694438],
+ [0.8441261828674842, 0.84406482711037389, 0.86716973322690072],
+ [0.84030420805957784, 0.8425605950855084, 0.865250882410458],
+ [0.83634031809191178, 0.84094796518951942, 0.86328528001070159],
+ [0.83222705712934408, 0.83923490627754482, 0.86127563500427884],
+ [0.82796894316013536, 0.83742600751395202, 0.85922399451306786],
+ [0.82357429680252847, 0.83552487764795436, 0.85713191328514948],
+ [0.81904654677937527, 0.8335364929949034, 0.85500206287010105],
+ [0.81438982121143089, 0.83146558694197847, 0.85283759062147024],
+ [0.8095999819094809, 0.82931896673505456, 0.85064441601050367],
+ [0.80469164429814577, 0.82709838780560663, 0.84842449296974021],
+ [0.79967075421267997, 0.82480781812080928, 0.84618210029578533],
+ [0.79454305089231114, 0.82245116226304615, 0.84392184786827984],
+ [0.78931445564608915, 0.82003213188702007, 0.8416486380471222],
+ [0.78399101042764918, 0.81755426400533426, 0.83936747464036732],
+ [0.77857892008227592, 0.81502089378742548, 0.8370834463093898],
+ [0.77308416590170936, 0.81243524735466011, 0.83480172950579679],
+ [0.76751108504417864, 0.8098007598713145, 0.83252816638059668],
+ [0.76186907937980286, 0.80711949387647486, 0.830266486168872],
+ [0.75616443584381976, 0.80439408733477935, 0.82802138994719998],
+ [0.75040346765406696, 0.80162699008965321, 0.82579737851082424],
+ [0.74459247771890169, 0.79882047719583249, 0.82359867586156521],
+ [0.73873771700494939, 0.79597665735031009, 0.82142922780433014],
+ [0.73284543645523459, 0.79309746468844067, 0.81929263384230377],
+ [0.72692177512829703, 0.7901846863592763, 0.81719217466726379],
+ [0.72097280665536778, 0.78723995923452639, 0.81513073920879264],
+ [0.71500403076252128, 0.78426487091581187, 0.81311116559949914],
+ [0.70902078134539304, 0.78126088716070907, 0.81113591855117928],
+ [0.7030297722540817, 0.77822904973358131, 0.80920618848056969],
+ [0.6970365443886174, 0.77517050008066057, 0.80732335380063447],
+ [0.69104641009309098, 0.77208629460678091, 0.80548841690679074],
+ [0.68506446154395928, 0.7689774029354699, 0.80370206267176914],
+ [0.67909554499882152, 0.76584472131395898, 0.8019646617300199],
+ [0.67314422559426212, 0.76268908733890484, 0.80027628545809526],
+ [0.66721479803752815, 0.7595112803730375, 0.79863674654537764],
+ [0.6613112930078745, 0.75631202708719025, 0.7970456043491897],
+ [0.65543692326454717, 0.75309208756768431, 0.79550271129031047],
+ [0.64959573004253479, 0.74985201221941766, 0.79400674021499107],
+ [0.6437910831099849, 0.7465923800833657, 0.79255653201306053],
+ [0.63802586828545982, 0.74331376714033193, 0.79115100459573173],
+ [0.6323027138710603, 0.74001672160131404, 0.78978892762640429],
+ [0.62662402022604591, 0.73670175403699445, 0.78846901316334561],
+ [0.62099193064817548, 0.73336934798923203, 0.78718994624696581],
+ [0.61540846411770478, 0.73001995232739691, 0.78595022706750484],
+ [0.60987543176093062, 0.72665398759758293, 0.78474835732694714],
+ [0.60439434200274855, 0.7232718614323369, 0.78358295593535587],
+ [0.5989665814482068, 0.71987394892246725, 0.78245259899346642],
+ [0.59359335696837223, 0.7164606049658685, 0.78135588237640097],
+ [0.58827579780555495, 0.71303214646458135, 0.78029141405636515],
+ [0.58301487036932409, 0.70958887676997473, 0.77925781820476592],
+ [0.5778116438998202, 0.70613106157153982, 0.77825345121025524],
+ [0.5726668948158774, 0.7026589535425779, 0.77727702680911992],
+ [0.56758117853861967, 0.69917279302646274, 0.77632748534275298],
+ [0.56255515357219343, 0.69567278381629649, 0.77540359142309845],
+ [0.55758940419605174, 0.69215911458254054, 0.7745041337932782],
+ [0.55268450589347129, 0.68863194515166382, 0.7736279426902245],
+ [0.54784098153018634, 0.68509142218509878, 0.77277386473440868],
+ [0.54305932424018233, 0.68153767253065878, 0.77194079697835083],
+ [0.53834015575176275, 0.67797081129095405, 0.77112734439057717],
+ [0.53368389147728401, 0.67439093705212727, 0.7703325054879735],
+ [0.529090861832473, 0.67079812302806219, 0.76955552292313134],
+ [0.52456151470593582, 0.66719242996142225, 0.76879541714230948],
+ [0.52009627392235558, 0.66357391434030388, 0.76805119403344102],
+ [0.5156955988596057, 0.65994260812897998, 0.76732191489596169],
+ [0.51135992541601927, 0.65629853981831865, 0.76660663780645333],
+ [0.50708969576451657, 0.65264172403146448, 0.76590445660835849],
+ [0.5028853540415561, 0.64897216734095264, 0.76521446718174913],
+ [0.49874733661356069, 0.6452898684900934, 0.76453578734180083],
+ [0.4946761847863938, 0.64159484119504429, 0.76386719002130909],
+ [0.49067224938561221, 0.63788704858847078, 0.76320812763163837],
+ [0.4867359599430568, 0.63416646251100506, 0.76255780085924041],
+ [0.4828677867260272, 0.6304330455306234, 0.76191537149895305],
+ [0.47906816236197386, 0.62668676251860134, 0.76128000375662419],
+ [0.47533752394906287, 0.62292757283835809, 0.76065085571817748],
+ [0.47167629518877091, 0.61915543242884641, 0.76002709227883047],
+ [0.46808490970531597, 0.61537028695790286, 0.75940789891092741],
+ [0.46456376716303932, 0.61157208822864151, 0.75879242623025811],
+ [0.46111326647023881, 0.607760777169989, 0.75817986436807139],
+ [0.45773377230160567, 0.60393630046586455, 0.75756936901859162],
+ [0.45442563977552913, 0.60009859503858665, 0.75696013660606487],
+ [0.45118918687617743, 0.59624762051353541, 0.75635120643246645],
+ [0.44802470933589172, 0.59238331452146575, 0.75574176474107924],
+ [0.44493246854215379, 0.5885055998308617, 0.7551311041857901],
+ [0.44191271766696399, 0.58461441100175571, 0.75451838884410671],
+ [0.43896563958048396, 0.58070969241098491, 0.75390276208285945],
+ [0.43609138958356369, 0.57679137998186081, 0.7532834105961016],
+ [0.43329008867358393, 0.57285941625606673, 0.75265946532566674],
+ [0.43056179073057571, 0.56891374572457176, 0.75203008099312696],
+ [0.42790652284925834, 0.5649543060909209, 0.75139443521914839],
+ [0.42532423665011354, 0.56098104959950301, 0.75075164989005116],
+ [0.42281485675772662, 0.55699392126996583, 0.75010086988227642],
+ [0.42037822361396326, 0.55299287158108168, 0.7494412559451894],
+ [0.41801414079233629, 0.54897785421888889, 0.74877193167001121],
+ [0.4157223260454232, 0.54494882715350401, 0.74809204459000522],
+ [0.41350245743314729, 0.54090574771098476, 0.74740073297543086],
+ [0.41135414697304568, 0.53684857765005933, 0.74669712855065784],
+ [0.4092768899914751, 0.53277730177130322, 0.74598030635707824],
+ [0.40727018694219069, 0.52869188011057411, 0.74524942637581271],
+ [0.40533343789303178, 0.52459228174983119, 0.74450365836708132],
+ [0.40346600333905397, 0.52047847653840029, 0.74374215223567086],
+ [0.40166714010896104, 0.51635044969688759, 0.7429640345324835],
+ [0.39993606933454834, 0.51220818143218516, 0.74216844571317986],
+ [0.3982719152586337, 0.50805166539276136, 0.74135450918099721],
+ [0.39667374905665609, 0.50388089053847973, 0.74052138580516735],
+ [0.39514058808207631, 0.49969585326377758, 0.73966820211715711],
+ [0.39367135736822567, 0.49549655777451179, 0.738794102296364],
+ [0.39226494876209317, 0.49128300332899261, 0.73789824784475078],
+ [0.39092017571994903, 0.48705520251223039, 0.73697977133881254],
+ [0.38963580160340855, 0.48281316715123496, 0.73603782546932739],
+ [0.38841053300842432, 0.47855691131792805, 0.73507157641157261],
+ [0.38724301459330251, 0.47428645933635388, 0.73408016787854391],
+ [0.38613184178892102, 0.4700018340988123, 0.7330627749243106],
+ [0.38507556793651387, 0.46570306719930193, 0.73201854033690505],
+ [0.38407269378943537, 0.46139018782416635, 0.73094665432902683],
+ [0.38312168084402748, 0.45706323581407199, 0.72984626791353258],
+ [0.38222094988570376, 0.45272225034283325, 0.72871656144003782],
+ [0.38136887930454161, 0.44836727669277859, 0.72755671317141346],
+ [0.38056380696565623, 0.44399837208633719, 0.72636587045135315],
+ [0.37980403744848751, 0.43961558821222629, 0.72514323778761092],
+ [0.37908789283110761, 0.43521897612544935, 0.72388798691323131],
+ [0.378413635091359, 0.43080859411413064, 0.72259931993061044],
+ [0.37777949753513729, 0.4263845142616835, 0.72127639993530235],
+ [0.37718371844251231, 0.42194680223454828, 0.71991841524475775],
+ [0.37662448930806297, 0.41749553747893614, 0.71852454736176108],
+ [0.37610001286385814, 0.41303079952477062, 0.71709396919920232],
+ [0.37560846919442398, 0.40855267638072096, 0.71562585091587549],
+ [0.37514802505380473, 0.4040612609993941, 0.7141193695725726],
+ [0.37471686019302231, 0.3995566498711684, 0.71257368516500463],
+ [0.37431313199312338, 0.39503894828283309, 0.71098796522377461],
+ [0.37393499330475782, 0.39050827529375831, 0.70936134293478448],
+ [0.3735806215098284, 0.38596474386057539, 0.70769297607310577],
+ [0.37324816143326384, 0.38140848555753937, 0.70598200974806036],
+ [0.37293578646665032, 0.37683963835219841, 0.70422755780589941],
+ [0.37264166757849604, 0.37225835004836849, 0.7024287314570723],
+ [0.37236397858465387, 0.36766477862108266, 0.70058463496520773],
+ [0.37210089702443822, 0.36305909736982378, 0.69869434615073722],
+ [0.3718506155898596, 0.35844148285875221, 0.69675695810256544],
+ [0.37161133234400479, 0.3538121372967869, 0.69477149919380887],
+ [0.37138124223736607, 0.34917126878479027, 0.69273703471928827],
+ [0.37115856636209105, 0.34451911410230168, 0.69065253586464992],
+ [0.37094151551337329, 0.33985591488818123, 0.68851703379505125],
+ [0.37072833279422668, 0.33518193808489577, 0.68632948169606767],
+ [0.37051738634484427, 0.33049741244307851, 0.68408888788857214],
+ [0.37030682071842685, 0.32580269697872455, 0.68179411684486679],
+ [0.37009487130772695, 0.3210981375964933, 0.67944405399056851],
+ [0.36987980329025361, 0.31638410101153364, 0.67703755438090574],
+ [0.36965987626565955, 0.31166098762951971, 0.67457344743419545],
+ [0.36943334591276228, 0.30692923551862339, 0.67205052849120617],
+ [0.36919847837592484, 0.30218932176507068, 0.66946754331614522],
+ [0.36895355306596778, 0.29744175492366276, 0.66682322089824264],
+ [0.36869682231895268, 0.29268709856150099, 0.66411625298236909],
+ [0.36842655638020444, 0.28792596437778462, 0.66134526910944602],
+ [0.36814101479899719, 0.28315901221182987, 0.65850888806972308],
+ [0.36783843696531082, 0.27838697181297761, 0.65560566838453704],
+ [0.36751707094367697, 0.27361063317090978, 0.65263411711618635],
+ [0.36717513650699446, 0.26883085667326956, 0.64959272297892245],
+ [0.36681085540107988, 0.26404857724525643, 0.64647991652908243],
+ [0.36642243251550632, 0.25926481158628106, 0.64329409140765537],
+ [0.36600853966739794, 0.25448043878086224, 0.64003361803368586],
+ [0.36556698373538982, 0.24969683475296395, 0.63669675187488584],
+ [0.36509579845886808, 0.24491536803550484, 0.63328173520055586],
+ [0.36459308890125008, 0.24013747024823828, 0.62978680155026101],
+ [0.36405693022088509, 0.23536470386204195, 0.62621013451953023],
+ [0.36348537610385145, 0.23059876218396419, 0.62254988622392882],
+ [0.36287643560041027, 0.22584149293287031, 0.61880417410823019],
+ [0.36222809558295926, 0.22109488427338303, 0.61497112346096128],
+ [0.36153829010998356, 0.21636111429594002, 0.61104880679640927],
+ [0.36080493826624654, 0.21164251793458128, 0.60703532172064711],
+ [0.36002681809096376, 0.20694122817889948, 0.60292845431916875],
+ [0.35920088560930186, 0.20226037920758122, 0.5987265295935138],
+ [0.35832489966617809, 0.197602942459778, 0.59442768517501066],
+ [0.35739663292915563, 0.19297208197842461, 0.59003011251063131],
+ [0.35641381143126327, 0.18837119869242164, 0.5855320765920552],
+ [0.35537415306906722, 0.18380392577704466, 0.58093191431832802],
+ [0.35427534960663759, 0.17927413271618647, 0.57622809660668717],
+ [0.35311574421123737, 0.17478570377561287, 0.57141871523555288],
+ [0.35189248608873791, 0.17034320478524959, 0.56650284911216653],
+ [0.35060304441931012, 0.16595129984720861, 0.56147964703993225],
+ [0.34924513554955644, 0.16161477763045118, 0.55634837474163779],
+ [0.34781653238777782, 0.15733863511152979, 0.55110853452703257],
+ [0.34631507175793091, 0.15312802296627787, 0.5457599924248665],
+ [0.34473901574536375, 0.14898820589826409, 0.54030245920406539],
+ [0.34308600291572294, 0.14492465359918028, 0.53473704282067103],
+ [0.34135411074506483, 0.1409427920655632, 0.52906500940336754],
+ [0.33954168752669694, 0.13704801896718169, 0.52328797535085236],
+ [0.33764732090671112, 0.13324562282438077, 0.51740807573979475],
+ [0.33566978565015315, 0.12954074251271822, 0.51142807215168951],
+ [0.33360804901486002, 0.12593818301005921, 0.50535164796654897],
+ [0.33146154891145124, 0.12244245263391232, 0.49918274588431072],
+ [0.32923005203231409, 0.11905764321981127, 0.49292595612342666],
+ [0.3269137124539796, 0.1157873496841953, 0.48658646495697461],
+ [0.32451307931207785, 0.11263459791730848, 0.48017007211645196],
+ [0.32202882276069322, 0.10960114111258401, 0.47368494725726878],
+ [0.31946262395497965, 0.10668879882392659, 0.46713728801395243],
+ [0.31681648089023501, 0.10389861387653518, 0.46053414662739794],
+ [0.31409278414755532, 0.10123077676403242, 0.45388335612058467],
+ [0.31129434479712365, 0.098684771934052201, 0.44719313715161618],
+ [0.30842444457210105, 0.096259385340577736, 0.44047194882050544],
+ [0.30548675819945936, 0.093952764840823738, 0.43372849999361113],
+ [0.30248536364574252, 0.091761187397303601, 0.42697404043749887],
+ [0.29942483960214772, 0.089682253716750038, 0.42021619665853854],
+ [0.29631000388905288, 0.087713250960463951, 0.41346259134143476],
+ [0.29314593096985248, 0.085850656889620708, 0.40672178082365834],
+ [0.28993792445176608, 0.08409078829085731, 0.40000214725256295],
+ [0.28669151388283165, 0.082429873848480689, 0.39331182532243375],
+ [0.28341239797185225, 0.080864153365499375, 0.38665868550105914],
+ [0.28010638576975472, 0.079389994802261526, 0.38005028528138707],
+ [0.27677939615815589, 0.078003941033788216, 0.37349382846504675],
+ [0.27343739342450812, 0.076702800237496066, 0.36699616136347685],
+ [0.27008637749114051, 0.075483675584275545, 0.36056376228111864],
+ [0.26673233211995284, 0.074344018028546205, 0.35420276066240958],
+ [0.26338121807151404, 0.073281657939897077, 0.34791888996380105],
+ [0.26003895187439957, 0.072294781043362205, 0.3417175669546984],
+ [0.25671191651083902, 0.071380106242082242, 0.33560648984600089],
+ [0.25340685873736807, 0.070533582926851829, 0.3295945757321303],
+ [0.25012845306199383, 0.069758206429106989, 0.32368100685760637],
+ [0.24688226237958999, 0.069053639449204451, 0.31786993834254956],
+ [0.24367372557466271, 0.068419855150922693, 0.31216524050888372],
+ [0.24050813332295939, 0.067857103814855602, 0.30657054493678321],
+ [0.23739062429054825, 0.067365888050555517, 0.30108922184065873],
+ [0.23433055727563878, 0.066935599661639394, 0.29574009929867601],
+ [0.23132955273021344, 0.066576186939090592, 0.29051361067988485],
+ [0.2283917709422868, 0.06628997924139618, 0.28541074411068496],
+ [0.22552164337737857, 0.066078173119395595, 0.28043398847505197],
+ [0.22272706739121817, 0.065933790675651943, 0.27559714652053702],
+ [0.22001251100779617, 0.065857918918907604, 0.27090279994325861],
+ [0.21737845072382705, 0.065859661233562045, 0.26634209349669508],
+ [0.21482843531473683, 0.065940385613778491, 0.26191675992376573],
+ [0.21237411048541005, 0.066085024661758446, 0.25765165093569542],
+ [0.21001214221188125, 0.066308573918947178, 0.2535289048041211],
+ [0.2077442377448806, 0.06661453200418091, 0.24954644291943817],
+ [0.20558051999470117, 0.066990462397868739, 0.24572497420147632],
+ [0.20352007949514977, 0.067444179612424215, 0.24205576625191821],
+ [0.20156133764129841, 0.067983271026200248, 0.23852974228695395],
+ [0.19971571438603364, 0.068592710553704722, 0.23517094067076993],
+ [0.19794834061899208, 0.069314066071660657, 0.23194647381302336],
+ [0.1960826032659409, 0.070321227242423623, 0.22874673279569585],
+ [0.19410351363791453, 0.071608304856891569, 0.22558727307410353],
+ [0.19199449184606268, 0.073182830649273306, 0.22243385243433622],
+ [0.18975853639094634, 0.075019861862143766, 0.2193005075652994],
+ [0.18739228342697645, 0.077102096899588329, 0.21618875376309582],
+ [0.18488035509396164, 0.079425730279723883, 0.21307651648984993],
+ [0.18774482037046955, 0.077251588468039312, 0.21387448578597812],
+ [0.19049578401722037, 0.075311278416787641, 0.2146562337112265],
+ [0.1931548636579131, 0.073606819040117955, 0.21542362939081539],
+ [0.19571853588267552, 0.072157781039602742, 0.21617499187076789],
+ [0.19819343656336558, 0.070974625252738788, 0.21690975060032436],
+ [0.20058760685133747, 0.070064576149984209, 0.21762721310371608],
+ [0.20290365333558247, 0.069435248580458964, 0.21833167885096033],
+ [0.20531725273301316, 0.068919592266397572, 0.21911516689288835],
+ [0.20785704662965598, 0.068484398797025281, 0.22000133917653536],
+ [0.21052882914958676, 0.06812195249816172, 0.22098759107715404],
+ [0.2133313859647627, 0.067830148426026665, 0.22207043213024291],
+ [0.21625279838647882, 0.067616330270516389, 0.22324568672294431],
+ [0.21930503925136402, 0.067465786362940039, 0.22451023616807558],
+ [0.22247308588973624, 0.067388214053092838, 0.22585960379408354],
+ [0.2257539681670791, 0.067382132300147474, 0.22728984778098055],
+ [0.22915620278592841, 0.067434730871152565, 0.22879681433956656],
+ [0.23266299920501882, 0.067557104388479783, 0.23037617493752832],
+ [0.23627495835774248, 0.06774359820987802, 0.23202360805926608],
+ [0.23999586188690308, 0.067985029964779953, 0.23373434258507808],
+ [0.24381149720247919, 0.068289851529011875, 0.23550427698321885],
+ [0.24772092990501099, 0.068653337909486523, 0.2373288009471749],
+ [0.25172899728289466, 0.069064630826035506, 0.23920260612763083],
+ [0.25582135547481771, 0.06953231029187984, 0.24112190491594204],
+ [0.25999463887892144, 0.070053855603861875, 0.24308218808684579],
+ [0.26425512207060942, 0.070616595622995437, 0.24507758869355967],
+ [0.26859095948172862, 0.071226716277922458, 0.24710443563450618],
+ [0.27299701518897301, 0.071883555446163511, 0.24915847093232929],
+ [0.27747150809142801, 0.072582969899254779, 0.25123493995942769],
+ [0.28201746297366942, 0.073315693214040967, 0.25332800295084507],
+ [0.28662309235899847, 0.074088460826808866, 0.25543478673717029],
+ [0.29128515387578635, 0.074899049847466703, 0.25755101595750435],
+ [0.2960004726065818, 0.075745336000958424, 0.25967245030364566],
+ [0.30077276812918691, 0.076617824336164764, 0.26179294097819672],
+ [0.30559226007249934, 0.077521963107537312, 0.26391006692119662],
+ [0.31045520848595526, 0.078456871676182177, 0.2660200572779356],
+ [0.31535870009205808, 0.079420997315243186, 0.26811904076941961],
+ [0.32029986557994061, 0.080412994737554838, 0.27020322893039511],
+ [0.32527888860401261, 0.081428390076546092, 0.27226772884656186],
+ [0.33029174471181438, 0.08246763389003825, 0.27430929404579435],
+ [0.33533353224455448, 0.083532434119003962, 0.27632534356790039],
+ [0.34040164359597463, 0.084622236191702671, 0.27831254595259397],
+ [0.34549355713871799, 0.085736654965126335, 0.28026769921081435],
+ [0.35060678246032478, 0.08687555176033529, 0.28218770540182386],
+ [0.35573889947341125, 0.088038974350243354, 0.2840695897279818],
+ [0.36088752387578377, 0.089227194362745205, 0.28591050458531014],
+ [0.36605031412464006, 0.090440685427697898, 0.2877077458811747],
+ [0.37122508431309342, 0.091679997480262732, 0.28945865397633169],
+ [0.3764103053221462, 0.092945198093777909, 0.29116024157313919],
+ [0.38160247377467543, 0.094238731263712183, 0.29281107506269488],
+ [0.38679939079544168, 0.09556181960083443, 0.29440901248173756],
+ [0.39199887556812907, 0.09691583650296684, 0.29595212005509081],
+ [0.39719876876325577, 0.098302320968278623, 0.29743856476285779],
+ [0.40239692379737496, 0.099722930314950553, 0.29886674369733968],
+ [0.40759120392688708, 0.10117945586419633, 0.30023519507728602],
+ [0.41277985630360303, 0.1026734006932461, 0.30154226437468967],
+ [0.41796105205173684, 0.10420644885760968, 0.30278652039631843],
+ [0.42313214269556043, 0.10578120994917611, 0.3039675809469457],
+ [0.42829101315789753, 0.1073997763055258, 0.30508479060294547],
+ [0.4334355841041439, 0.1090642347484701, 0.30613767928289148],
+ [0.43856378187931538, 0.11077667828375456, 0.30712600062348083],
+ [0.44367358645071275, 0.11253912421257944, 0.30804973095465449],
+ [0.44876299173174822, 0.11435355574622549, 0.30890905921943196],
+ [0.45383005086999889, 0.11622183788331528, 0.30970441249844921],
+ [0.45887288947308297, 0.11814571137706886, 0.31043636979038808],
+ [0.46389102840284874, 0.12012561256850712, 0.31110343446582983],
+ [0.46888111384598413, 0.12216445576414045, 0.31170911458932665],
+ [0.473841437035254, 0.12426354237989065, 0.31225470169927194],
+ [0.47877034239726296, 0.12642401401409453, 0.31274172735821959],
+ [0.48366628618847957, 0.12864679022013889, 0.31317188565991266],
+ [0.48852847371852987, 0.13093210934893723, 0.31354553695453014],
+ [0.49335504375145617, 0.13328091630401023, 0.31386561956734976],
+ [0.49814435462074153, 0.13569380302451714, 0.314135190862664],
+ [0.50289524974970612, 0.13817086581280427, 0.31435662153833671],
+ [0.50760681181053691, 0.14071192654913128, 0.31453200120082569],
+ [0.51227835105321762, 0.14331656120063752, 0.3146630922831542],
+ [0.51690848800544464, 0.14598463068714407, 0.31475407592280041],
+ [0.52149652863229956, 0.14871544765633712, 0.31480767954534428],
+ [0.52604189625477482, 0.15150818660835483, 0.31482653406646727],
+ [0.53054420489856446, 0.15436183633886777, 0.31481299789187128],
+ [0.5350027976174474, 0.15727540775107324, 0.31477085207396532],
+ [0.53941736649199057, 0.16024769309971934, 0.31470295028655965],
+ [0.54378771313608565, 0.16327738551419116, 0.31461204226295625],
+ [0.54811370033467621, 0.1663630904279047, 0.31450102990914708],
+ [0.55239521572711914, 0.16950338809328983, 0.31437291554615371],
+ [0.55663229034969341, 0.17269677158182117, 0.31423043195101424],
+ [0.56082499039117173, 0.17594170887918095, 0.31407639883970623],
+ [0.56497343529017696, 0.17923664950367169, 0.3139136046337036],
+ [0.56907784784011428, 0.18258004462335425, 0.31374440956796529],
+ [0.57313845754107873, 0.18597036007065024, 0.31357126868520002],
+ [0.57715550812992045, 0.18940601489760422, 0.31339704333572083],
+ [0.58112932761586555, 0.19288548904692518, 0.31322399394183942],
+ [0.58506024396466882, 0.19640737049066315, 0.31305401163732732],
+ [0.58894861935544707, 0.19997020971775276, 0.31288922211590126],
+ [0.59279480536520257, 0.20357251410079796, 0.31273234839304942],
+ [0.59659918109122367, 0.207212956082026, 0.31258523031121233],
+ [0.60036213010411577, 0.21089030138947745, 0.31244934410414688],
+ [0.60408401696732739, 0.21460331490206347, 0.31232652641170694],
+ [0.60776523994818654, 0.21835070166659282, 0.31221903291870201],
+ [0.6114062072731884, 0.22213124697023234, 0.31212881396435238],
+ [0.61500723236391375, 0.22594402043981826, 0.31205680685765741],
+ [0.61856865258877192, 0.22978799249179921, 0.31200463838728931],
+ [0.62209079821082613, 0.2336621873300741, 0.31197383273627388],
+ [0.62557416500434959, 0.23756535071152696, 0.31196698314912269],
+ [0.62901892016985872, 0.24149689191922535, 0.31198447195645718],
+ [0.63242534854210275, 0.24545598775548677, 0.31202765974624452],
+ [0.6357937104834237, 0.24944185818822678, 0.31209793953300591],
+ [0.6391243387840212, 0.25345365461983138, 0.31219689612063978],
+ [0.642417577481186, 0.257490519876798, 0.31232631707560987],
+ [0.64567349382645434, 0.26155203161615281, 0.31248673753935263],
+ [0.64889230169458245, 0.26563755336209077, 0.31267941819570189],
+ [0.65207417290277303, 0.26974650525236699, 0.31290560605819168],
+ [0.65521932609327127, 0.27387826652410152, 0.3131666792687211],
+ [0.6583280801134499, 0.27803210957665631, 0.3134643447952643],
+ [0.66140037532601781, 0.28220778870555907, 0.31379912926498488],
+ [0.66443632469878844, 0.28640483614256179, 0.31417223403606975],
+ [0.66743603766369131, 0.29062280081258873, 0.31458483752056837],
+ [0.67039959547676198, 0.29486126309253047, 0.31503813956872212],
+ [0.67332725564817331, 0.29911962764489264, 0.31553372323982209],
+ [0.67621897924409746, 0.30339762792450425, 0.3160724937230589],
+ [0.67907474028157344, 0.30769497879760166, 0.31665545668946665],
+ [0.68189457150944521, 0.31201133280550686, 0.31728380489244951],
+ [0.68467850942494535, 0.31634634821222207, 0.31795870784057567],
+ [0.68742656435169625, 0.32069970535138104, 0.31868137622277692],
+ [0.6901389321505248, 0.32507091815606004, 0.31945332332898302],
+ [0.69281544846764931, 0.32945984647042675, 0.3202754315314667],
+ [0.69545608346891119, 0.33386622163232865, 0.32114884306985791],
+ [0.6980608153581771, 0.33828976326048621, 0.32207478855218091],
+ [0.70062962477242097, 0.34273019305341756, 0.32305449047765694],
+ [0.70316249458814151, 0.34718723719597999, 0.32408913679491225],
+ [0.70565951122610093, 0.35166052978120937, 0.32518014084085567],
+ [0.70812059568420482, 0.35614985523380299, 0.32632861885644465],
+ [0.7105456546582587, 0.36065500290840113, 0.32753574162788762],
+ [0.71293466839773467, 0.36517570519856757, 0.3288027427038317],
+ [0.71528760614847287, 0.36971170225223449, 0.3301308728723546],
+ [0.71760444908133847, 0.37426272710686193, 0.33152138620958932],
+ [0.71988521490549851, 0.37882848839337313, 0.33297555200245399],
+ [0.7221299918421461, 0.38340864508963057, 0.33449469983585844],
+ [0.72433865647781592, 0.38800301593162145, 0.33607995965691828],
+ [0.72651122900227549, 0.3926113126792577, 0.3377325942005665],
+ [0.72864773856716547, 0.39723324476747235, 0.33945384341064017],
+ [0.73074820754845171, 0.401868526884681, 0.3412449533046818],
+ [0.73281270506268747, 0.4065168468778026, 0.34310715173410822],
+ [0.73484133598564938, 0.41117787004519513, 0.34504169470809071],
+ [0.73683422173585866, 0.41585125850290111, 0.34704978520758401],
+ [0.73879140024599266, 0.42053672992315327, 0.34913260148542435],
+ [0.74071301619506091, 0.4252339389526239, 0.35129130890802607],
+ [0.7425992159973317, 0.42994254036133867, 0.35352709245374592],
+ [0.74445018676570673, 0.43466217184617112, 0.35584108091122535],
+ [0.74626615789163442, 0.43939245044973502, 0.35823439142300639],
+ [0.74804739275559562, 0.44413297780351974, 0.36070813602540136],
+ [0.74979420547170472, 0.44888333481548809, 0.36326337558360278],
+ [0.75150685045891663, 0.45364314496866825, 0.36590112443835765],
+ [0.75318566369046569, 0.45841199172949604, 0.36862236642234769],
+ [0.75483105066959544, 0.46318942799460555, 0.3714280448394211],
+ [0.75644341577140706, 0.46797501437948458, 0.37431909037543515],
+ [0.75802325538455839, 0.4727682731566229, 0.37729635531096678],
+ [0.75957111105340058, 0.47756871222057079, 0.380360657784311],
+ [0.7610876378057071, 0.48237579130289127, 0.38351275723852291],
+ [0.76257333554052609, 0.48718906673415824, 0.38675335037837993],
+ [0.76402885609288662, 0.49200802533379656, 0.39008308392311997],
+ [0.76545492593330511, 0.49683212909727231, 0.39350254000115381],
+ [0.76685228950643891, 0.5016608471009063, 0.39701221751773474],
+ [0.76822176599735303, 0.50649362371287909, 0.40061257089416885],
+ [0.7695642334401418, 0.5113298901696085, 0.40430398069682483],
+ [0.77088091962302474, 0.51616892643469103, 0.40808667584648967],
+ [0.77217257229605551, 0.5210102658711383, 0.41196089987122869],
+ [0.77344021829889886, 0.52585332093451564, 0.41592679539764366],
+ [0.77468494746063199, 0.53069749384776732, 0.41998440356963762],
+ [0.77590790730685699, 0.53554217882461186, 0.42413367909988375],
+ [0.7771103295521099, 0.54038674910561235, 0.42837450371258479],
+ [0.77829345807633121, 0.54523059488426595, 0.432706647838971],
+ [0.77945862731506643, 0.55007308413977274, 0.43712979856444761],
+ [0.78060774749483774, 0.55491335744890613, 0.44164332426364639],
+ [0.78174180478981836, 0.55975098052594863, 0.44624687186865436],
+ [0.78286225264440912, 0.56458533111166875, 0.45093985823706345],
+ [0.78397060836414478, 0.56941578326710418, 0.45572154742892063],
+ [0.78506845019606841, 0.5742417003617839, 0.46059116206904965],
+ [0.78615737132332963, 0.5790624629815756, 0.46554778281918402],
+ [0.78723904108188347, 0.58387743744557208, 0.47059039582133383],
+ [0.78831514045623963, 0.58868600173562435, 0.47571791879076081],
+ [0.78938737766251943, 0.5934875421745599, 0.48092913815357724],
+ [0.79045776847727878, 0.59828134277062461, 0.48622257801969754],
+ [0.79152832843475607, 0.60306670593147205, 0.49159667021646397],
+ [0.79260034304237448, 0.60784322087037024, 0.49705020621532009],
+ [0.79367559698664958, 0.61261029334072192, 0.50258161291269432],
+ [0.79475585972654039, 0.61736734400220705, 0.50818921213102985],
+ [0.79584292379583765, 0.62211378808451145, 0.51387124091909786],
+ [0.79693854719951607, 0.62684905679296699, 0.5196258425240281],
+ [0.79804447815136637, 0.63157258225089552, 0.52545108144834785],
+ [0.7991624518501963, 0.63628379372029187, 0.53134495942561433],
+ [0.80029415389753977, 0.64098213306749863, 0.53730535185141037],
+ [0.80144124292560048, 0.64566703459218766, 0.5433300863249918],
+ [0.80260531146112946, 0.65033793748103852, 0.54941691584603647],
+ [0.80378792531077625, 0.65499426549472628, 0.55556350867083815],
+ [0.80499054790810298, 0.65963545027564163, 0.56176745110546977],
+ [0.80621460526927058, 0.66426089585282289, 0.56802629178649788],
+ [0.8074614045096935, 0.6688700095398864, 0.57433746373459582],
+ [0.80873219170089694, 0.67346216702194517, 0.58069834805576737],
+ [0.81002809466520687, 0.67803672673971815, 0.58710626908082753],
+ [0.81135014011763329, 0.68259301546243389, 0.59355848909050757],
+ [0.81269922039881493, 0.68713033714618876, 0.60005214820435104],
+ [0.81407611046993344, 0.69164794791482131, 0.6065843782630862],
+ [0.81548146627279483, 0.69614505508308089, 0.61315221209322646],
+ [0.81691575775055891, 0.70062083014783982, 0.61975260637257923],
+ [0.81837931164498223, 0.70507438189635097, 0.62638245478933297],
+ [0.81987230650455289, 0.70950474978787481, 0.63303857040067113],
+ [0.8213947205565636, 0.7139109141951604, 0.63971766697672761],
+ [0.82294635110428427, 0.71829177331290062, 0.6464164243818421],
+ [0.8245268129450285, 0.72264614312088882, 0.65313137915422603],
+ [0.82613549710580259, 0.72697275518238258, 0.65985900156216504],
+ [0.8277716072353446, 0.73127023324078089, 0.66659570204682972],
+ [0.82943407816481474, 0.7355371221572935, 0.67333772009301907],
+ [0.83112163529096306, 0.73977184647638616, 0.68008125203631464],
+ [0.83283277185777982, 0.74397271817459876, 0.68682235874648545],
+ [0.8345656905566583, 0.7481379479992134, 0.69355697649863846],
+ [0.83631898844737929, 0.75226548952875261, 0.70027999028864962],
+ [0.83809123476131964, 0.75635314860808633, 0.70698561390212977],
+ [0.83987839884120874, 0.76039907199779677, 0.71367147811129228],
+ [0.84167750766845151, 0.76440101200982946, 0.72033299387284622],
+ [0.84348529222933699, 0.76835660399870176, 0.72696536998972039],
+ [0.84529810731955113, 0.77226338601044719, 0.73356368240541492],
+ [0.84711195507965098, 0.77611880236047159, 0.74012275762807056],
+ [0.84892245563117641, 0.77992021407650147, 0.74663719293664366],
+ [0.85072697023178789, 0.78366457342383888, 0.7530974636118285],
+ [0.85251907207708444, 0.78734936133548439, 0.7594994148789691],
+ [0.85429219611470464, 0.79097196777091994, 0.76583801477914104],
+ [0.85604022314725403, 0.79452963601550608, 0.77210610037674143],
+ [0.85775662943504905, 0.79801963142713928, 0.77829571667247499],
+ [0.8594346370300241, 0.8014392309950078, 0.78439788751383921],
+ [0.86107117027565516, 0.80478517909812231, 0.79039529663736285],
+ [0.86265601051127572, 0.80805523804261525, 0.796282666437655],
+ [0.86418343723941027, 0.81124644224653542, 0.80204612696863953],
+ [0.86564934325605325, 0.81435544067514909, 0.80766972324164554],
+ [0.86705314907048503, 0.81737804041911244, 0.81313419626911398],
+ [0.86839954695818633, 0.82030875512181523, 0.81841638963128993],
+ [0.86969131502613806, 0.82314158859569164, 0.82350476683173168],
+ [0.87093846717297507, 0.82586857889438514, 0.82838497261149613],
+ [0.87215331978454325, 0.82848052823709672, 0.8330486712880828],
+ [0.87335171360916275, 0.83096715251272624, 0.83748851001197089],
+ [0.87453793320260187, 0.83331972948645461, 0.84171925358069011],
+ [0.87571458709961403, 0.8355302318472394, 0.84575537519027078],
+ [0.87687848451614692, 0.83759238071186537, 0.84961373549150254],
+ [0.87802298436649007, 0.83950165618540074, 0.85330645352458923],
+ [0.87913244240792765, 0.84125554884475906, 0.85685572291039636],
+ [0.88019293315695812, 0.84285224824778615, 0.86027399927156634],
+ [0.88119169871341951, 0.84429066717717349, 0.86356595168669881],
+ [0.88211542489401606, 0.84557007254559347, 0.86673765046233331],
+ [0.88295168595448525, 0.84668970275699273, 0.86979617048190971],
+ [0.88369127145898041, 0.84764891761519268, 0.87274147101441557],
+ [0.88432713054113543, 0.84844741572055415, 0.87556785228242973],
+ [0.88485138159908572, 0.84908426422893801, 0.87828235285372469],
+ [0.88525897972630474, 0.84955892810989209, 0.88088414794024839],
+ [0.88554714811952384, 0.84987174283631584, 0.88336206121170946],
+ [0.88571155122845646, 0.85002186115856315, 0.88572538990087124]]
+
+_twilight_shifted_data = (_twilight_data[len(_twilight_data)//2:] +
+ _twilight_data[:len(_twilight_data)//2])
+_twilight_shifted_data.reverse()
+_turbo_data = [[0.18995, 0.07176, 0.23217],
+ [0.19483, 0.08339, 0.26149],
+ [0.19956, 0.09498, 0.29024],
+ [0.20415, 0.10652, 0.31844],
+ [0.20860, 0.11802, 0.34607],
+ [0.21291, 0.12947, 0.37314],
+ [0.21708, 0.14087, 0.39964],
+ [0.22111, 0.15223, 0.42558],
+ [0.22500, 0.16354, 0.45096],
+ [0.22875, 0.17481, 0.47578],
+ [0.23236, 0.18603, 0.50004],
+ [0.23582, 0.19720, 0.52373],
+ [0.23915, 0.20833, 0.54686],
+ [0.24234, 0.21941, 0.56942],
+ [0.24539, 0.23044, 0.59142],
+ [0.24830, 0.24143, 0.61286],
+ [0.25107, 0.25237, 0.63374],
+ [0.25369, 0.26327, 0.65406],
+ [0.25618, 0.27412, 0.67381],
+ [0.25853, 0.28492, 0.69300],
+ [0.26074, 0.29568, 0.71162],
+ [0.26280, 0.30639, 0.72968],
+ [0.26473, 0.31706, 0.74718],
+ [0.26652, 0.32768, 0.76412],
+ [0.26816, 0.33825, 0.78050],
+ [0.26967, 0.34878, 0.79631],
+ [0.27103, 0.35926, 0.81156],
+ [0.27226, 0.36970, 0.82624],
+ [0.27334, 0.38008, 0.84037],
+ [0.27429, 0.39043, 0.85393],
+ [0.27509, 0.40072, 0.86692],
+ [0.27576, 0.41097, 0.87936],
+ [0.27628, 0.42118, 0.89123],
+ [0.27667, 0.43134, 0.90254],
+ [0.27691, 0.44145, 0.91328],
+ [0.27701, 0.45152, 0.92347],
+ [0.27698, 0.46153, 0.93309],
+ [0.27680, 0.47151, 0.94214],
+ [0.27648, 0.48144, 0.95064],
+ [0.27603, 0.49132, 0.95857],
+ [0.27543, 0.50115, 0.96594],
+ [0.27469, 0.51094, 0.97275],
+ [0.27381, 0.52069, 0.97899],
+ [0.27273, 0.53040, 0.98461],
+ [0.27106, 0.54015, 0.98930],
+ [0.26878, 0.54995, 0.99303],
+ [0.26592, 0.55979, 0.99583],
+ [0.26252, 0.56967, 0.99773],
+ [0.25862, 0.57958, 0.99876],
+ [0.25425, 0.58950, 0.99896],
+ [0.24946, 0.59943, 0.99835],
+ [0.24427, 0.60937, 0.99697],
+ [0.23874, 0.61931, 0.99485],
+ [0.23288, 0.62923, 0.99202],
+ [0.22676, 0.63913, 0.98851],
+ [0.22039, 0.64901, 0.98436],
+ [0.21382, 0.65886, 0.97959],
+ [0.20708, 0.66866, 0.97423],
+ [0.20021, 0.67842, 0.96833],
+ [0.19326, 0.68812, 0.96190],
+ [0.18625, 0.69775, 0.95498],
+ [0.17923, 0.70732, 0.94761],
+ [0.17223, 0.71680, 0.93981],
+ [0.16529, 0.72620, 0.93161],
+ [0.15844, 0.73551, 0.92305],
+ [0.15173, 0.74472, 0.91416],
+ [0.14519, 0.75381, 0.90496],
+ [0.13886, 0.76279, 0.89550],
+ [0.13278, 0.77165, 0.88580],
+ [0.12698, 0.78037, 0.87590],
+ [0.12151, 0.78896, 0.86581],
+ [0.11639, 0.79740, 0.85559],
+ [0.11167, 0.80569, 0.84525],
+ [0.10738, 0.81381, 0.83484],
+ [0.10357, 0.82177, 0.82437],
+ [0.10026, 0.82955, 0.81389],
+ [0.09750, 0.83714, 0.80342],
+ [0.09532, 0.84455, 0.79299],
+ [0.09377, 0.85175, 0.78264],
+ [0.09287, 0.85875, 0.77240],
+ [0.09267, 0.86554, 0.76230],
+ [0.09320, 0.87211, 0.75237],
+ [0.09451, 0.87844, 0.74265],
+ [0.09662, 0.88454, 0.73316],
+ [0.09958, 0.89040, 0.72393],
+ [0.10342, 0.89600, 0.71500],
+ [0.10815, 0.90142, 0.70599],
+ [0.11374, 0.90673, 0.69651],
+ [0.12014, 0.91193, 0.68660],
+ [0.12733, 0.91701, 0.67627],
+ [0.13526, 0.92197, 0.66556],
+ [0.14391, 0.92680, 0.65448],
+ [0.15323, 0.93151, 0.64308],
+ [0.16319, 0.93609, 0.63137],
+ [0.17377, 0.94053, 0.61938],
+ [0.18491, 0.94484, 0.60713],
+ [0.19659, 0.94901, 0.59466],
+ [0.20877, 0.95304, 0.58199],
+ [0.22142, 0.95692, 0.56914],
+ [0.23449, 0.96065, 0.55614],
+ [0.24797, 0.96423, 0.54303],
+ [0.26180, 0.96765, 0.52981],
+ [0.27597, 0.97092, 0.51653],
+ [0.29042, 0.97403, 0.50321],
+ [0.30513, 0.97697, 0.48987],
+ [0.32006, 0.97974, 0.47654],
+ [0.33517, 0.98234, 0.46325],
+ [0.35043, 0.98477, 0.45002],
+ [0.36581, 0.98702, 0.43688],
+ [0.38127, 0.98909, 0.42386],
+ [0.39678, 0.99098, 0.41098],
+ [0.41229, 0.99268, 0.39826],
+ [0.42778, 0.99419, 0.38575],
+ [0.44321, 0.99551, 0.37345],
+ [0.45854, 0.99663, 0.36140],
+ [0.47375, 0.99755, 0.34963],
+ [0.48879, 0.99828, 0.33816],
+ [0.50362, 0.99879, 0.32701],
+ [0.51822, 0.99910, 0.31622],
+ [0.53255, 0.99919, 0.30581],
+ [0.54658, 0.99907, 0.29581],
+ [0.56026, 0.99873, 0.28623],
+ [0.57357, 0.99817, 0.27712],
+ [0.58646, 0.99739, 0.26849],
+ [0.59891, 0.99638, 0.26038],
+ [0.61088, 0.99514, 0.25280],
+ [0.62233, 0.99366, 0.24579],
+ [0.63323, 0.99195, 0.23937],
+ [0.64362, 0.98999, 0.23356],
+ [0.65394, 0.98775, 0.22835],
+ [0.66428, 0.98524, 0.22370],
+ [0.67462, 0.98246, 0.21960],
+ [0.68494, 0.97941, 0.21602],
+ [0.69525, 0.97610, 0.21294],
+ [0.70553, 0.97255, 0.21032],
+ [0.71577, 0.96875, 0.20815],
+ [0.72596, 0.96470, 0.20640],
+ [0.73610, 0.96043, 0.20504],
+ [0.74617, 0.95593, 0.20406],
+ [0.75617, 0.95121, 0.20343],
+ [0.76608, 0.94627, 0.20311],
+ [0.77591, 0.94113, 0.20310],
+ [0.78563, 0.93579, 0.20336],
+ [0.79524, 0.93025, 0.20386],
+ [0.80473, 0.92452, 0.20459],
+ [0.81410, 0.91861, 0.20552],
+ [0.82333, 0.91253, 0.20663],
+ [0.83241, 0.90627, 0.20788],
+ [0.84133, 0.89986, 0.20926],
+ [0.85010, 0.89328, 0.21074],
+ [0.85868, 0.88655, 0.21230],
+ [0.86709, 0.87968, 0.21391],
+ [0.87530, 0.87267, 0.21555],
+ [0.88331, 0.86553, 0.21719],
+ [0.89112, 0.85826, 0.21880],
+ [0.89870, 0.85087, 0.22038],
+ [0.90605, 0.84337, 0.22188],
+ [0.91317, 0.83576, 0.22328],
+ [0.92004, 0.82806, 0.22456],
+ [0.92666, 0.82025, 0.22570],
+ [0.93301, 0.81236, 0.22667],
+ [0.93909, 0.80439, 0.22744],
+ [0.94489, 0.79634, 0.22800],
+ [0.95039, 0.78823, 0.22831],
+ [0.95560, 0.78005, 0.22836],
+ [0.96049, 0.77181, 0.22811],
+ [0.96507, 0.76352, 0.22754],
+ [0.96931, 0.75519, 0.22663],
+ [0.97323, 0.74682, 0.22536],
+ [0.97679, 0.73842, 0.22369],
+ [0.98000, 0.73000, 0.22161],
+ [0.98289, 0.72140, 0.21918],
+ [0.98549, 0.71250, 0.21650],
+ [0.98781, 0.70330, 0.21358],
+ [0.98986, 0.69382, 0.21043],
+ [0.99163, 0.68408, 0.20706],
+ [0.99314, 0.67408, 0.20348],
+ [0.99438, 0.66386, 0.19971],
+ [0.99535, 0.65341, 0.19577],
+ [0.99607, 0.64277, 0.19165],
+ [0.99654, 0.63193, 0.18738],
+ [0.99675, 0.62093, 0.18297],
+ [0.99672, 0.60977, 0.17842],
+ [0.99644, 0.59846, 0.17376],
+ [0.99593, 0.58703, 0.16899],
+ [0.99517, 0.57549, 0.16412],
+ [0.99419, 0.56386, 0.15918],
+ [0.99297, 0.55214, 0.15417],
+ [0.99153, 0.54036, 0.14910],
+ [0.98987, 0.52854, 0.14398],
+ [0.98799, 0.51667, 0.13883],
+ [0.98590, 0.50479, 0.13367],
+ [0.98360, 0.49291, 0.12849],
+ [0.98108, 0.48104, 0.12332],
+ [0.97837, 0.46920, 0.11817],
+ [0.97545, 0.45740, 0.11305],
+ [0.97234, 0.44565, 0.10797],
+ [0.96904, 0.43399, 0.10294],
+ [0.96555, 0.42241, 0.09798],
+ [0.96187, 0.41093, 0.09310],
+ [0.95801, 0.39958, 0.08831],
+ [0.95398, 0.38836, 0.08362],
+ [0.94977, 0.37729, 0.07905],
+ [0.94538, 0.36638, 0.07461],
+ [0.94084, 0.35566, 0.07031],
+ [0.93612, 0.34513, 0.06616],
+ [0.93125, 0.33482, 0.06218],
+ [0.92623, 0.32473, 0.05837],
+ [0.92105, 0.31489, 0.05475],
+ [0.91572, 0.30530, 0.05134],
+ [0.91024, 0.29599, 0.04814],
+ [0.90463, 0.28696, 0.04516],
+ [0.89888, 0.27824, 0.04243],
+ [0.89298, 0.26981, 0.03993],
+ [0.88691, 0.26152, 0.03753],
+ [0.88066, 0.25334, 0.03521],
+ [0.87422, 0.24526, 0.03297],
+ [0.86760, 0.23730, 0.03082],
+ [0.86079, 0.22945, 0.02875],
+ [0.85380, 0.22170, 0.02677],
+ [0.84662, 0.21407, 0.02487],
+ [0.83926, 0.20654, 0.02305],
+ [0.83172, 0.19912, 0.02131],
+ [0.82399, 0.19182, 0.01966],
+ [0.81608, 0.18462, 0.01809],
+ [0.80799, 0.17753, 0.01660],
+ [0.79971, 0.17055, 0.01520],
+ [0.79125, 0.16368, 0.01387],
+ [0.78260, 0.15693, 0.01264],
+ [0.77377, 0.15028, 0.01148],
+ [0.76476, 0.14374, 0.01041],
+ [0.75556, 0.13731, 0.00942],
+ [0.74617, 0.13098, 0.00851],
+ [0.73661, 0.12477, 0.00769],
+ [0.72686, 0.11867, 0.00695],
+ [0.71692, 0.11268, 0.00629],
+ [0.70680, 0.10680, 0.00571],
+ [0.69650, 0.10102, 0.00522],
+ [0.68602, 0.09536, 0.00481],
+ [0.67535, 0.08980, 0.00449],
+ [0.66449, 0.08436, 0.00424],
+ [0.65345, 0.07902, 0.00408],
+ [0.64223, 0.07380, 0.00401],
+ [0.63082, 0.06868, 0.00401],
+ [0.61923, 0.06367, 0.00410],
+ [0.60746, 0.05878, 0.00427],
+ [0.59550, 0.05399, 0.00453],
+ [0.58336, 0.04931, 0.00486],
+ [0.57103, 0.04474, 0.00529],
+ [0.55852, 0.04028, 0.00579],
+ [0.54583, 0.03593, 0.00638],
+ [0.53295, 0.03169, 0.00705],
+ [0.51989, 0.02756, 0.00780],
+ [0.50664, 0.02354, 0.00863],
+ [0.49321, 0.01963, 0.00955],
+ [0.47960, 0.01583, 0.01055]]
+
+_berlin_data = [
+ [0.62108, 0.69018, 0.99951],
+ [0.61216, 0.68923, 0.99537],
+ [0.6032, 0.68825, 0.99124],
+ [0.5942, 0.68726, 0.98709],
+ [0.58517, 0.68625, 0.98292],
+ [0.57609, 0.68522, 0.97873],
+ [0.56696, 0.68417, 0.97452],
+ [0.55779, 0.6831, 0.97029],
+ [0.54859, 0.68199, 0.96602],
+ [0.53933, 0.68086, 0.9617],
+ [0.53003, 0.67969, 0.95735],
+ [0.52069, 0.67848, 0.95294],
+ [0.51129, 0.67723, 0.94847],
+ [0.50186, 0.67591, 0.94392],
+ [0.49237, 0.67453, 0.9393],
+ [0.48283, 0.67308, 0.93457],
+ [0.47324, 0.67153, 0.92975],
+ [0.46361, 0.6699, 0.92481],
+ [0.45393, 0.66815, 0.91974],
+ [0.44421, 0.66628, 0.91452],
+ [0.43444, 0.66427, 0.90914],
+ [0.42465, 0.66212, 0.90359],
+ [0.41482, 0.65979, 0.89785],
+ [0.40498, 0.65729, 0.89191],
+ [0.39514, 0.65458, 0.88575],
+ [0.3853, 0.65167, 0.87937],
+ [0.37549, 0.64854, 0.87276],
+ [0.36574, 0.64516, 0.8659],
+ [0.35606, 0.64155, 0.8588],
+ [0.34645, 0.63769, 0.85145],
+ [0.33698, 0.63357, 0.84386],
+ [0.32764, 0.62919, 0.83602],
+ [0.31849, 0.62455, 0.82794],
+ [0.30954, 0.61966, 0.81963],
+ [0.30078, 0.6145, 0.81111],
+ [0.29231, 0.60911, 0.80238],
+ [0.2841, 0.60348, 0.79347],
+ [0.27621, 0.59763, 0.78439],
+ [0.26859, 0.59158, 0.77514],
+ [0.26131, 0.58534, 0.76578],
+ [0.25437, 0.57891, 0.7563],
+ [0.24775, 0.57233, 0.74672],
+ [0.24146, 0.5656, 0.73707],
+ [0.23552, 0.55875, 0.72735],
+ [0.22984, 0.5518, 0.7176],
+ [0.2245, 0.54475, 0.7078],
+ [0.21948, 0.53763, 0.698],
+ [0.21469, 0.53043, 0.68819],
+ [0.21017, 0.52319, 0.67838],
+ [0.20589, 0.5159, 0.66858],
+ [0.20177, 0.5086, 0.65879],
+ [0.19788, 0.50126, 0.64903],
+ [0.19417, 0.4939, 0.63929],
+ [0.19056, 0.48654, 0.62957],
+ [0.18711, 0.47918, 0.6199],
+ [0.18375, 0.47183, 0.61024],
+ [0.1805, 0.46447, 0.60062],
+ [0.17737, 0.45712, 0.59104],
+ [0.17426, 0.44979, 0.58148],
+ [0.17122, 0.44247, 0.57197],
+ [0.16824, 0.43517, 0.56249],
+ [0.16529, 0.42788, 0.55302],
+ [0.16244, 0.42061, 0.5436],
+ [0.15954, 0.41337, 0.53421],
+ [0.15674, 0.40615, 0.52486],
+ [0.15391, 0.39893, 0.51552],
+ [0.15112, 0.39176, 0.50623],
+ [0.14835, 0.38459, 0.49697],
+ [0.14564, 0.37746, 0.48775],
+ [0.14288, 0.37034, 0.47854],
+ [0.14014, 0.36326, 0.46939],
+ [0.13747, 0.3562, 0.46024],
+ [0.13478, 0.34916, 0.45115],
+ [0.13208, 0.34215, 0.44209],
+ [0.1294, 0.33517, 0.43304],
+ [0.12674, 0.3282, 0.42404],
+ [0.12409, 0.32126, 0.41507],
+ [0.12146, 0.31435, 0.40614],
+ [0.1189, 0.30746, 0.39723],
+ [0.11632, 0.30061, 0.38838],
+ [0.11373, 0.29378, 0.37955],
+ [0.11119, 0.28698, 0.37075],
+ [0.10861, 0.28022, 0.362],
+ [0.10616, 0.2735, 0.35328],
+ [0.10367, 0.26678, 0.34459],
+ [0.10118, 0.26011, 0.33595],
+ [0.098776, 0.25347, 0.32734],
+ [0.096347, 0.24685, 0.31878],
+ [0.094059, 0.24026, 0.31027],
+ [0.091788, 0.23373, 0.30176],
+ [0.089506, 0.22725, 0.29332],
+ [0.087341, 0.2208, 0.28491],
+ [0.085142, 0.21436, 0.27658],
+ [0.083069, 0.20798, 0.26825],
+ [0.081098, 0.20163, 0.25999],
+ [0.07913, 0.19536, 0.25178],
+ [0.077286, 0.18914, 0.24359],
+ [0.075571, 0.18294, 0.2355],
+ [0.073993, 0.17683, 0.22743],
+ [0.07241, 0.17079, 0.21943],
+ [0.071045, 0.1648, 0.2115],
+ [0.069767, 0.1589, 0.20363],
+ [0.068618, 0.15304, 0.19582],
+ [0.06756, 0.14732, 0.18812],
+ [0.066665, 0.14167, 0.18045],
+ [0.065923, 0.13608, 0.17292],
+ [0.065339, 0.1307, 0.16546],
+ [0.064911, 0.12535, 0.15817],
+ [0.064636, 0.12013, 0.15095],
+ [0.064517, 0.11507, 0.14389],
+ [0.064554, 0.11022, 0.13696],
+ [0.064749, 0.10543, 0.13023],
+ [0.0651, 0.10085, 0.12357],
+ [0.065383, 0.096469, 0.11717],
+ [0.065574, 0.092338, 0.11101],
+ [0.065892, 0.088201, 0.10498],
+ [0.066388, 0.084134, 0.099288],
+ [0.067108, 0.080051, 0.093829],
+ [0.068193, 0.076099, 0.08847],
+ [0.06972, 0.072283, 0.083025],
+ [0.071639, 0.068654, 0.077544],
+ [0.073978, 0.065058, 0.07211],
+ [0.076596, 0.061657, 0.066651],
+ [0.079637, 0.05855, 0.061133],
+ [0.082963, 0.055666, 0.055745],
+ [0.086537, 0.052997, 0.050336],
+ [0.090315, 0.050699, 0.04504],
+ [0.09426, 0.048753, 0.039773],
+ [0.098319, 0.047041, 0.034683],
+ [0.10246, 0.045624, 0.030074],
+ [0.10673, 0.044705, 0.026012],
+ [0.11099, 0.043972, 0.022379],
+ [0.11524, 0.043596, 0.01915],
+ [0.11955, 0.043567, 0.016299],
+ [0.12381, 0.043861, 0.013797],
+ [0.1281, 0.044459, 0.011588],
+ [0.13232, 0.045229, 0.0095315],
+ [0.13645, 0.046164, 0.0078947],
+ [0.14063, 0.047374, 0.006502],
+ [0.14488, 0.048634, 0.0053266],
+ [0.14923, 0.049836, 0.0043455],
+ [0.15369, 0.050997, 0.0035374],
+ [0.15831, 0.05213, 0.0028824],
+ [0.16301, 0.053218, 0.0023628],
+ [0.16781, 0.05424, 0.0019629],
+ [0.17274, 0.055172, 0.001669],
+ [0.1778, 0.056018, 0.0014692],
+ [0.18286, 0.05682, 0.0013401],
+ [0.18806, 0.057574, 0.0012617],
+ [0.19323, 0.058514, 0.0012261],
+ [0.19846, 0.05955, 0.0012271],
+ [0.20378, 0.060501, 0.0012601],
+ [0.20909, 0.061486, 0.0013221],
+ [0.21447, 0.06271, 0.0014116],
+ [0.2199, 0.063823, 0.0015287],
+ [0.22535, 0.065027, 0.0016748],
+ [0.23086, 0.066297, 0.0018529],
+ [0.23642, 0.067645, 0.0020675],
+ [0.24202, 0.069092, 0.0023247],
+ [0.24768, 0.070458, 0.0026319],
+ [0.25339, 0.071986, 0.0029984],
+ [0.25918, 0.07364, 0.003435],
+ [0.265, 0.075237, 0.0039545],
+ [0.27093, 0.076965, 0.004571],
+ [0.27693, 0.078822, 0.0053006],
+ [0.28302, 0.080819, 0.0061608],
+ [0.2892, 0.082879, 0.0071713],
+ [0.29547, 0.085075, 0.0083494],
+ [0.30186, 0.08746, 0.0097258],
+ [0.30839, 0.089912, 0.011455],
+ [0.31502, 0.09253, 0.013324],
+ [0.32181, 0.095392, 0.015413],
+ [0.32874, 0.098396, 0.01778],
+ [0.3358, 0.10158, 0.020449],
+ [0.34304, 0.10498, 0.02344],
+ [0.35041, 0.10864, 0.026771],
+ [0.35795, 0.11256, 0.030456],
+ [0.36563, 0.11666, 0.034571],
+ [0.37347, 0.12097, 0.039115],
+ [0.38146, 0.12561, 0.043693],
+ [0.38958, 0.13046, 0.048471],
+ [0.39785, 0.13547, 0.053136],
+ [0.40622, 0.1408, 0.057848],
+ [0.41469, 0.14627, 0.062715],
+ [0.42323, 0.15198, 0.067685],
+ [0.43184, 0.15791, 0.073044],
+ [0.44044, 0.16403, 0.07862],
+ [0.44909, 0.17027, 0.084644],
+ [0.4577, 0.17667, 0.090869],
+ [0.46631, 0.18321, 0.097335],
+ [0.4749, 0.18989, 0.10406],
+ [0.48342, 0.19668, 0.11104],
+ [0.49191, 0.20352, 0.11819],
+ [0.50032, 0.21043, 0.1255],
+ [0.50869, 0.21742, 0.13298],
+ [0.51698, 0.22443, 0.14062],
+ [0.5252, 0.23154, 0.14835],
+ [0.53335, 0.23862, 0.15626],
+ [0.54144, 0.24575, 0.16423],
+ [0.54948, 0.25292, 0.17226],
+ [0.55746, 0.26009, 0.1804],
+ [0.56538, 0.26726, 0.18864],
+ [0.57327, 0.27446, 0.19692],
+ [0.58111, 0.28167, 0.20524],
+ [0.58892, 0.28889, 0.21362],
+ [0.59672, 0.29611, 0.22205],
+ [0.60448, 0.30335, 0.23053],
+ [0.61223, 0.31062, 0.23905],
+ [0.61998, 0.31787, 0.24762],
+ [0.62771, 0.32513, 0.25619],
+ [0.63544, 0.33244, 0.26481],
+ [0.64317, 0.33975, 0.27349],
+ [0.65092, 0.34706, 0.28218],
+ [0.65866, 0.3544, 0.29089],
+ [0.66642, 0.36175, 0.29964],
+ [0.67419, 0.36912, 0.30842],
+ [0.68198, 0.37652, 0.31722],
+ [0.68978, 0.38392, 0.32604],
+ [0.6976, 0.39135, 0.33493],
+ [0.70543, 0.39879, 0.3438],
+ [0.71329, 0.40627, 0.35272],
+ [0.72116, 0.41376, 0.36166],
+ [0.72905, 0.42126, 0.37062],
+ [0.73697, 0.4288, 0.37962],
+ [0.7449, 0.43635, 0.38864],
+ [0.75285, 0.44392, 0.39768],
+ [0.76083, 0.45151, 0.40675],
+ [0.76882, 0.45912, 0.41584],
+ [0.77684, 0.46676, 0.42496],
+ [0.78488, 0.47441, 0.43409],
+ [0.79293, 0.48208, 0.44327],
+ [0.80101, 0.48976, 0.45246],
+ [0.80911, 0.49749, 0.46167],
+ [0.81722, 0.50521, 0.47091],
+ [0.82536, 0.51296, 0.48017],
+ [0.83352, 0.52073, 0.48945],
+ [0.84169, 0.52853, 0.49876],
+ [0.84988, 0.53634, 0.5081],
+ [0.85809, 0.54416, 0.51745],
+ [0.86632, 0.55201, 0.52683],
+ [0.87457, 0.55988, 0.53622],
+ [0.88283, 0.56776, 0.54564],
+ [0.89111, 0.57567, 0.55508],
+ [0.89941, 0.58358, 0.56455],
+ [0.90772, 0.59153, 0.57404],
+ [0.91603, 0.59949, 0.58355],
+ [0.92437, 0.60747, 0.59309],
+ [0.93271, 0.61546, 0.60265],
+ [0.94108, 0.62348, 0.61223],
+ [0.94945, 0.63151, 0.62183],
+ [0.95783, 0.63956, 0.63147],
+ [0.96622, 0.64763, 0.64111],
+ [0.97462, 0.65572, 0.65079],
+ [0.98303, 0.66382, 0.66049],
+ [0.99145, 0.67194, 0.67022],
+ [0.99987, 0.68007, 0.67995]]
+
+_managua_data = [
+ [1, 0.81263, 0.40424],
+ [0.99516, 0.80455, 0.40155],
+ [0.99024, 0.79649, 0.39888],
+ [0.98532, 0.78848, 0.39622],
+ [0.98041, 0.7805, 0.39356],
+ [0.97551, 0.77257, 0.39093],
+ [0.97062, 0.76468, 0.3883],
+ [0.96573, 0.75684, 0.38568],
+ [0.96087, 0.74904, 0.3831],
+ [0.95601, 0.74129, 0.38052],
+ [0.95116, 0.7336, 0.37795],
+ [0.94631, 0.72595, 0.37539],
+ [0.94149, 0.71835, 0.37286],
+ [0.93667, 0.7108, 0.37034],
+ [0.93186, 0.7033, 0.36784],
+ [0.92706, 0.69585, 0.36536],
+ [0.92228, 0.68845, 0.36289],
+ [0.9175, 0.68109, 0.36042],
+ [0.91273, 0.67379, 0.358],
+ [0.90797, 0.66653, 0.35558],
+ [0.90321, 0.65932, 0.35316],
+ [0.89846, 0.65216, 0.35078],
+ [0.89372, 0.64503, 0.34839],
+ [0.88899, 0.63796, 0.34601],
+ [0.88426, 0.63093, 0.34367],
+ [0.87953, 0.62395, 0.34134],
+ [0.87481, 0.617, 0.33902],
+ [0.87009, 0.61009, 0.3367],
+ [0.86538, 0.60323, 0.33442],
+ [0.86067, 0.59641, 0.33213],
+ [0.85597, 0.58963, 0.32987],
+ [0.85125, 0.5829, 0.3276],
+ [0.84655, 0.57621, 0.32536],
+ [0.84185, 0.56954, 0.32315],
+ [0.83714, 0.56294, 0.32094],
+ [0.83243, 0.55635, 0.31874],
+ [0.82772, 0.54983, 0.31656],
+ [0.82301, 0.54333, 0.31438],
+ [0.81829, 0.53688, 0.31222],
+ [0.81357, 0.53046, 0.3101],
+ [0.80886, 0.52408, 0.30796],
+ [0.80413, 0.51775, 0.30587],
+ [0.7994, 0.51145, 0.30375],
+ [0.79466, 0.50519, 0.30167],
+ [0.78991, 0.49898, 0.29962],
+ [0.78516, 0.4928, 0.29757],
+ [0.7804, 0.48668, 0.29553],
+ [0.77564, 0.48058, 0.29351],
+ [0.77086, 0.47454, 0.29153],
+ [0.76608, 0.46853, 0.28954],
+ [0.76128, 0.46255, 0.28756],
+ [0.75647, 0.45663, 0.28561],
+ [0.75166, 0.45075, 0.28369],
+ [0.74682, 0.44491, 0.28178],
+ [0.74197, 0.4391, 0.27988],
+ [0.73711, 0.43333, 0.27801],
+ [0.73223, 0.42762, 0.27616],
+ [0.72732, 0.42192, 0.2743],
+ [0.72239, 0.41628, 0.27247],
+ [0.71746, 0.41067, 0.27069],
+ [0.71247, 0.40508, 0.26891],
+ [0.70747, 0.39952, 0.26712],
+ [0.70244, 0.39401, 0.26538],
+ [0.69737, 0.38852, 0.26367],
+ [0.69227, 0.38306, 0.26194],
+ [0.68712, 0.37761, 0.26025],
+ [0.68193, 0.37219, 0.25857],
+ [0.67671, 0.3668, 0.25692],
+ [0.67143, 0.36142, 0.25529],
+ [0.6661, 0.35607, 0.25367],
+ [0.66071, 0.35073, 0.25208],
+ [0.65528, 0.34539, 0.25049],
+ [0.6498, 0.34009, 0.24895],
+ [0.64425, 0.3348, 0.24742],
+ [0.63866, 0.32953, 0.2459],
+ [0.633, 0.32425, 0.24442],
+ [0.62729, 0.31901, 0.24298],
+ [0.62152, 0.3138, 0.24157],
+ [0.6157, 0.3086, 0.24017],
+ [0.60983, 0.30341, 0.23881],
+ [0.60391, 0.29826, 0.23752],
+ [0.59793, 0.29314, 0.23623],
+ [0.59191, 0.28805, 0.235],
+ [0.58585, 0.28302, 0.23377],
+ [0.57974, 0.27799, 0.23263],
+ [0.57359, 0.27302, 0.23155],
+ [0.56741, 0.26808, 0.23047],
+ [0.5612, 0.26321, 0.22948],
+ [0.55496, 0.25837, 0.22857],
+ [0.54871, 0.25361, 0.22769],
+ [0.54243, 0.24891, 0.22689],
+ [0.53614, 0.24424, 0.22616],
+ [0.52984, 0.23968, 0.22548],
+ [0.52354, 0.2352, 0.22487],
+ [0.51724, 0.23076, 0.22436],
+ [0.51094, 0.22643, 0.22395],
+ [0.50467, 0.22217, 0.22363],
+ [0.49841, 0.21802, 0.22339],
+ [0.49217, 0.21397, 0.22325],
+ [0.48595, 0.21, 0.22321],
+ [0.47979, 0.20618, 0.22328],
+ [0.47364, 0.20242, 0.22345],
+ [0.46756, 0.1988, 0.22373],
+ [0.46152, 0.19532, 0.22413],
+ [0.45554, 0.19195, 0.22465],
+ [0.44962, 0.18873, 0.22534],
+ [0.44377, 0.18566, 0.22616],
+ [0.43799, 0.18266, 0.22708],
+ [0.43229, 0.17987, 0.22817],
+ [0.42665, 0.17723, 0.22938],
+ [0.42111, 0.17474, 0.23077],
+ [0.41567, 0.17238, 0.23232],
+ [0.41033, 0.17023, 0.23401],
+ [0.40507, 0.16822, 0.2359],
+ [0.39992, 0.1664, 0.23794],
+ [0.39489, 0.16475, 0.24014],
+ [0.38996, 0.16331, 0.24254],
+ [0.38515, 0.16203, 0.24512],
+ [0.38046, 0.16093, 0.24792],
+ [0.37589, 0.16, 0.25087],
+ [0.37143, 0.15932, 0.25403],
+ [0.36711, 0.15883, 0.25738],
+ [0.36292, 0.15853, 0.26092],
+ [0.35885, 0.15843, 0.26466],
+ [0.35494, 0.15853, 0.26862],
+ [0.35114, 0.15882, 0.27276],
+ [0.34748, 0.15931, 0.27711],
+ [0.34394, 0.15999, 0.28164],
+ [0.34056, 0.16094, 0.28636],
+ [0.33731, 0.16207, 0.29131],
+ [0.3342, 0.16338, 0.29642],
+ [0.33121, 0.16486, 0.3017],
+ [0.32837, 0.16658, 0.30719],
+ [0.32565, 0.16847, 0.31284],
+ [0.3231, 0.17056, 0.31867],
+ [0.32066, 0.17283, 0.32465],
+ [0.31834, 0.1753, 0.33079],
+ [0.31616, 0.17797, 0.3371],
+ [0.3141, 0.18074, 0.34354],
+ [0.31216, 0.18373, 0.35011],
+ [0.31038, 0.1869, 0.35682],
+ [0.3087, 0.19021, 0.36363],
+ [0.30712, 0.1937, 0.37056],
+ [0.3057, 0.19732, 0.3776],
+ [0.30435, 0.20106, 0.38473],
+ [0.30314, 0.205, 0.39195],
+ [0.30204, 0.20905, 0.39924],
+ [0.30106, 0.21323, 0.40661],
+ [0.30019, 0.21756, 0.41404],
+ [0.29944, 0.22198, 0.42151],
+ [0.29878, 0.22656, 0.42904],
+ [0.29822, 0.23122, 0.4366],
+ [0.29778, 0.23599, 0.44419],
+ [0.29745, 0.24085, 0.45179],
+ [0.29721, 0.24582, 0.45941],
+ [0.29708, 0.2509, 0.46703],
+ [0.29704, 0.25603, 0.47465],
+ [0.2971, 0.26127, 0.48225],
+ [0.29726, 0.26658, 0.48983],
+ [0.2975, 0.27194, 0.4974],
+ [0.29784, 0.27741, 0.50493],
+ [0.29828, 0.28292, 0.51242],
+ [0.29881, 0.28847, 0.51987],
+ [0.29943, 0.29408, 0.52728],
+ [0.30012, 0.29976, 0.53463],
+ [0.3009, 0.30548, 0.54191],
+ [0.30176, 0.31122, 0.54915],
+ [0.30271, 0.317, 0.5563],
+ [0.30373, 0.32283, 0.56339],
+ [0.30483, 0.32866, 0.5704],
+ [0.30601, 0.33454, 0.57733],
+ [0.30722, 0.34042, 0.58418],
+ [0.30853, 0.34631, 0.59095],
+ [0.30989, 0.35224, 0.59763],
+ [0.3113, 0.35817, 0.60423],
+ [0.31277, 0.3641, 0.61073],
+ [0.31431, 0.37005, 0.61715],
+ [0.3159, 0.376, 0.62347],
+ [0.31752, 0.38195, 0.62969],
+ [0.3192, 0.3879, 0.63583],
+ [0.32092, 0.39385, 0.64188],
+ [0.32268, 0.39979, 0.64783],
+ [0.32446, 0.40575, 0.6537],
+ [0.3263, 0.41168, 0.65948],
+ [0.32817, 0.41763, 0.66517],
+ [0.33008, 0.42355, 0.67079],
+ [0.33201, 0.4295, 0.67632],
+ [0.33398, 0.43544, 0.68176],
+ [0.33596, 0.44137, 0.68715],
+ [0.33798, 0.44731, 0.69246],
+ [0.34003, 0.45327, 0.69769],
+ [0.3421, 0.45923, 0.70288],
+ [0.34419, 0.4652, 0.70799],
+ [0.34631, 0.4712, 0.71306],
+ [0.34847, 0.4772, 0.71808],
+ [0.35064, 0.48323, 0.72305],
+ [0.35283, 0.48928, 0.72798],
+ [0.35506, 0.49537, 0.73288],
+ [0.3573, 0.50149, 0.73773],
+ [0.35955, 0.50763, 0.74256],
+ [0.36185, 0.51381, 0.74736],
+ [0.36414, 0.52001, 0.75213],
+ [0.36649, 0.52627, 0.75689],
+ [0.36884, 0.53256, 0.76162],
+ [0.37119, 0.53889, 0.76633],
+ [0.37359, 0.54525, 0.77103],
+ [0.376, 0.55166, 0.77571],
+ [0.37842, 0.55809, 0.78037],
+ [0.38087, 0.56458, 0.78503],
+ [0.38333, 0.5711, 0.78966],
+ [0.38579, 0.57766, 0.79429],
+ [0.38828, 0.58426, 0.7989],
+ [0.39078, 0.59088, 0.8035],
+ [0.39329, 0.59755, 0.8081],
+ [0.39582, 0.60426, 0.81268],
+ [0.39835, 0.61099, 0.81725],
+ [0.4009, 0.61774, 0.82182],
+ [0.40344, 0.62454, 0.82637],
+ [0.406, 0.63137, 0.83092],
+ [0.40856, 0.63822, 0.83546],
+ [0.41114, 0.6451, 0.83999],
+ [0.41372, 0.65202, 0.84451],
+ [0.41631, 0.65896, 0.84903],
+ [0.4189, 0.66593, 0.85354],
+ [0.42149, 0.67294, 0.85805],
+ [0.4241, 0.67996, 0.86256],
+ [0.42671, 0.68702, 0.86705],
+ [0.42932, 0.69411, 0.87156],
+ [0.43195, 0.70123, 0.87606],
+ [0.43457, 0.70839, 0.88056],
+ [0.4372, 0.71557, 0.88506],
+ [0.43983, 0.72278, 0.88956],
+ [0.44248, 0.73004, 0.89407],
+ [0.44512, 0.73732, 0.89858],
+ [0.44776, 0.74464, 0.9031],
+ [0.45042, 0.752, 0.90763],
+ [0.45308, 0.75939, 0.91216],
+ [0.45574, 0.76682, 0.9167],
+ [0.45841, 0.77429, 0.92124],
+ [0.46109, 0.78181, 0.9258],
+ [0.46377, 0.78936, 0.93036],
+ [0.46645, 0.79694, 0.93494],
+ [0.46914, 0.80458, 0.93952],
+ [0.47183, 0.81224, 0.94412],
+ [0.47453, 0.81995, 0.94872],
+ [0.47721, 0.8277, 0.95334],
+ [0.47992, 0.83549, 0.95796],
+ [0.48261, 0.84331, 0.96259],
+ [0.4853, 0.85117, 0.96722],
+ [0.48801, 0.85906, 0.97186],
+ [0.49071, 0.86699, 0.97651],
+ [0.49339, 0.87495, 0.98116],
+ [0.49607, 0.88294, 0.98581],
+ [0.49877, 0.89096, 0.99047],
+ [0.50144, 0.89901, 0.99512],
+ [0.50411, 0.90708, 0.99978]]
+
+_vanimo_data = [
+ [1, 0.80346, 0.99215],
+ [0.99397, 0.79197, 0.98374],
+ [0.98791, 0.78052, 0.97535],
+ [0.98185, 0.7691, 0.96699],
+ [0.97578, 0.75774, 0.95867],
+ [0.96971, 0.74643, 0.95037],
+ [0.96363, 0.73517, 0.94211],
+ [0.95755, 0.72397, 0.93389],
+ [0.95147, 0.71284, 0.9257],
+ [0.94539, 0.70177, 0.91756],
+ [0.93931, 0.69077, 0.90945],
+ [0.93322, 0.67984, 0.90137],
+ [0.92713, 0.66899, 0.89334],
+ [0.92104, 0.65821, 0.88534],
+ [0.91495, 0.64751, 0.87738],
+ [0.90886, 0.63689, 0.86946],
+ [0.90276, 0.62634, 0.86158],
+ [0.89666, 0.61588, 0.85372],
+ [0.89055, 0.60551, 0.84591],
+ [0.88444, 0.59522, 0.83813],
+ [0.87831, 0.58503, 0.83039],
+ [0.87219, 0.57491, 0.82268],
+ [0.86605, 0.5649, 0.815],
+ [0.8599, 0.55499, 0.80736],
+ [0.85373, 0.54517, 0.79974],
+ [0.84756, 0.53544, 0.79216],
+ [0.84138, 0.52583, 0.78461],
+ [0.83517, 0.5163, 0.77709],
+ [0.82896, 0.5069, 0.76959],
+ [0.82272, 0.49761, 0.76212],
+ [0.81647, 0.48841, 0.75469],
+ [0.81018, 0.47934, 0.74728],
+ [0.80389, 0.47038, 0.7399],
+ [0.79757, 0.46154, 0.73255],
+ [0.79123, 0.45283, 0.72522],
+ [0.78487, 0.44424, 0.71792],
+ [0.77847, 0.43578, 0.71064],
+ [0.77206, 0.42745, 0.70339],
+ [0.76562, 0.41925, 0.69617],
+ [0.75914, 0.41118, 0.68897],
+ [0.75264, 0.40327, 0.68179],
+ [0.74612, 0.39549, 0.67465],
+ [0.73957, 0.38783, 0.66752],
+ [0.73297, 0.38034, 0.66041],
+ [0.72634, 0.37297, 0.65331],
+ [0.71967, 0.36575, 0.64623],
+ [0.71293, 0.35864, 0.63915],
+ [0.70615, 0.35166, 0.63206],
+ [0.69929, 0.34481, 0.62496],
+ [0.69236, 0.33804, 0.61782],
+ [0.68532, 0.33137, 0.61064],
+ [0.67817, 0.32479, 0.6034],
+ [0.67091, 0.3183, 0.59609],
+ [0.66351, 0.31184, 0.5887],
+ [0.65598, 0.30549, 0.58123],
+ [0.64828, 0.29917, 0.57366],
+ [0.64045, 0.29289, 0.56599],
+ [0.63245, 0.28667, 0.55822],
+ [0.6243, 0.28051, 0.55035],
+ [0.61598, 0.27442, 0.54237],
+ [0.60752, 0.26838, 0.53428],
+ [0.59889, 0.2624, 0.5261],
+ [0.59012, 0.25648, 0.51782],
+ [0.5812, 0.25063, 0.50944],
+ [0.57214, 0.24483, 0.50097],
+ [0.56294, 0.23914, 0.4924],
+ [0.55359, 0.23348, 0.48376],
+ [0.54413, 0.22795, 0.47505],
+ [0.53454, 0.22245, 0.46623],
+ [0.52483, 0.21706, 0.45736],
+ [0.51501, 0.21174, 0.44843],
+ [0.50508, 0.20651, 0.43942],
+ [0.49507, 0.20131, 0.43036],
+ [0.48495, 0.19628, 0.42125],
+ [0.47476, 0.19128, 0.4121],
+ [0.4645, 0.18639, 0.4029],
+ [0.45415, 0.18157, 0.39367],
+ [0.44376, 0.17688, 0.38441],
+ [0.43331, 0.17225, 0.37513],
+ [0.42282, 0.16773, 0.36585],
+ [0.41232, 0.16332, 0.35655],
+ [0.40178, 0.15897, 0.34726],
+ [0.39125, 0.15471, 0.33796],
+ [0.38071, 0.15058, 0.32869],
+ [0.37017, 0.14651, 0.31945],
+ [0.35969, 0.14258, 0.31025],
+ [0.34923, 0.13872, 0.30106],
+ [0.33883, 0.13499, 0.29196],
+ [0.32849, 0.13133, 0.28293],
+ [0.31824, 0.12778, 0.27396],
+ [0.30808, 0.12431, 0.26508],
+ [0.29805, 0.12097, 0.25631],
+ [0.28815, 0.11778, 0.24768],
+ [0.27841, 0.11462, 0.23916],
+ [0.26885, 0.11169, 0.23079],
+ [0.25946, 0.10877, 0.22259],
+ [0.25025, 0.10605, 0.21455],
+ [0.24131, 0.10341, 0.20673],
+ [0.23258, 0.10086, 0.19905],
+ [0.2241, 0.098494, 0.19163],
+ [0.21593, 0.096182, 0.18443],
+ [0.20799, 0.094098, 0.17748],
+ [0.20032, 0.092102, 0.17072],
+ [0.19299, 0.09021, 0.16425],
+ [0.18596, 0.088461, 0.15799],
+ [0.17918, 0.086861, 0.15197],
+ [0.17272, 0.08531, 0.14623],
+ [0.16658, 0.084017, 0.14075],
+ [0.1607, 0.082745, 0.13546],
+ [0.15515, 0.081683, 0.13049],
+ [0.1499, 0.080653, 0.1257],
+ [0.14493, 0.07978, 0.12112],
+ [0.1402, 0.079037, 0.11685],
+ [0.13578, 0.078426, 0.11282],
+ [0.13168, 0.077944, 0.10894],
+ [0.12782, 0.077586, 0.10529],
+ [0.12422, 0.077332, 0.1019],
+ [0.12091, 0.077161, 0.098724],
+ [0.11793, 0.077088, 0.095739],
+ [0.11512, 0.077124, 0.092921],
+ [0.11267, 0.077278, 0.090344],
+ [0.11042, 0.077557, 0.087858],
+ [0.10835, 0.077968, 0.085431],
+ [0.10665, 0.078516, 0.083233],
+ [0.105, 0.079207, 0.081185],
+ [0.10368, 0.080048, 0.079202],
+ [0.10245, 0.081036, 0.077408],
+ [0.10143, 0.082173, 0.075793],
+ [0.1006, 0.083343, 0.074344],
+ [0.099957, 0.084733, 0.073021],
+ [0.099492, 0.086174, 0.071799],
+ [0.099204, 0.087868, 0.070716],
+ [0.099092, 0.089631, 0.069813],
+ [0.099154, 0.091582, 0.069047],
+ [0.099384, 0.093597, 0.068337],
+ [0.099759, 0.095871, 0.067776],
+ [0.10029, 0.098368, 0.067351],
+ [0.10099, 0.101, 0.067056],
+ [0.10185, 0.1039, 0.066891],
+ [0.1029, 0.10702, 0.066853],
+ [0.10407, 0.11031, 0.066942],
+ [0.10543, 0.1138, 0.067155],
+ [0.10701, 0.1175, 0.067485],
+ [0.10866, 0.12142, 0.067929],
+ [0.11059, 0.12561, 0.06849],
+ [0.11265, 0.12998, 0.069162],
+ [0.11483, 0.13453, 0.069842],
+ [0.11725, 0.13923, 0.07061],
+ [0.11985, 0.14422, 0.071528],
+ [0.12259, 0.14937, 0.072403],
+ [0.12558, 0.15467, 0.073463],
+ [0.12867, 0.16015, 0.074429],
+ [0.13196, 0.16584, 0.075451],
+ [0.1354, 0.17169, 0.076499],
+ [0.13898, 0.17771, 0.077615],
+ [0.14273, 0.18382, 0.078814],
+ [0.14658, 0.1901, 0.080098],
+ [0.15058, 0.19654, 0.081473],
+ [0.15468, 0.20304, 0.08282],
+ [0.15891, 0.20968, 0.084315],
+ [0.16324, 0.21644, 0.085726],
+ [0.16764, 0.22326, 0.087378],
+ [0.17214, 0.23015, 0.088955],
+ [0.17673, 0.23717, 0.090617],
+ [0.18139, 0.24418, 0.092314],
+ [0.18615, 0.25132, 0.094071],
+ [0.19092, 0.25846, 0.095839],
+ [0.19578, 0.26567, 0.097702],
+ [0.20067, 0.2729, 0.099539],
+ [0.20564, 0.28016, 0.10144],
+ [0.21062, 0.28744, 0.10342],
+ [0.21565, 0.29475, 0.10534],
+ [0.22072, 0.30207, 0.10737],
+ [0.22579, 0.30942, 0.10942],
+ [0.23087, 0.31675, 0.11146],
+ [0.236, 0.32407, 0.11354],
+ [0.24112, 0.3314, 0.11563],
+ [0.24625, 0.33874, 0.11774],
+ [0.25142, 0.34605, 0.11988],
+ [0.25656, 0.35337, 0.12202],
+ [0.26171, 0.36065, 0.12422],
+ [0.26686, 0.36793, 0.12645],
+ [0.272, 0.37519, 0.12865],
+ [0.27717, 0.38242, 0.13092],
+ [0.28231, 0.38964, 0.13316],
+ [0.28741, 0.39682, 0.13541],
+ [0.29253, 0.40398, 0.13773],
+ [0.29763, 0.41111, 0.13998],
+ [0.30271, 0.4182, 0.14232],
+ [0.30778, 0.42527, 0.14466],
+ [0.31283, 0.43231, 0.14699],
+ [0.31787, 0.43929, 0.14937],
+ [0.32289, 0.44625, 0.15173],
+ [0.32787, 0.45318, 0.15414],
+ [0.33286, 0.46006, 0.1566],
+ [0.33781, 0.46693, 0.15904],
+ [0.34276, 0.47374, 0.16155],
+ [0.34769, 0.48054, 0.16407],
+ [0.3526, 0.48733, 0.16661],
+ [0.35753, 0.4941, 0.16923],
+ [0.36245, 0.50086, 0.17185],
+ [0.36738, 0.50764, 0.17458],
+ [0.37234, 0.51443, 0.17738],
+ [0.37735, 0.52125, 0.18022],
+ [0.38238, 0.52812, 0.18318],
+ [0.38746, 0.53505, 0.18626],
+ [0.39261, 0.54204, 0.18942],
+ [0.39783, 0.54911, 0.19272],
+ [0.40311, 0.55624, 0.19616],
+ [0.40846, 0.56348, 0.1997],
+ [0.4139, 0.57078, 0.20345],
+ [0.41942, 0.57819, 0.20734],
+ [0.42503, 0.5857, 0.2114],
+ [0.43071, 0.59329, 0.21565],
+ [0.43649, 0.60098, 0.22009],
+ [0.44237, 0.60878, 0.2247],
+ [0.44833, 0.61667, 0.22956],
+ [0.45439, 0.62465, 0.23468],
+ [0.46053, 0.63274, 0.23997],
+ [0.46679, 0.64092, 0.24553],
+ [0.47313, 0.64921, 0.25138],
+ [0.47959, 0.6576, 0.25745],
+ [0.48612, 0.66608, 0.26382],
+ [0.49277, 0.67466, 0.27047],
+ [0.49951, 0.68335, 0.2774],
+ [0.50636, 0.69213, 0.28464],
+ [0.51331, 0.70101, 0.2922],
+ [0.52035, 0.70998, 0.30008],
+ [0.5275, 0.71905, 0.30828],
+ [0.53474, 0.72821, 0.31682],
+ [0.54207, 0.73747, 0.32567],
+ [0.5495, 0.74682, 0.33491],
+ [0.55702, 0.75625, 0.34443],
+ [0.56461, 0.76577, 0.35434],
+ [0.5723, 0.77537, 0.36457],
+ [0.58006, 0.78506, 0.37515],
+ [0.58789, 0.79482, 0.38607],
+ [0.59581, 0.80465, 0.39734],
+ [0.60379, 0.81455, 0.40894],
+ [0.61182, 0.82453, 0.42086],
+ [0.61991, 0.83457, 0.43311],
+ [0.62805, 0.84467, 0.44566],
+ [0.63623, 0.85482, 0.45852],
+ [0.64445, 0.86503, 0.47168],
+ [0.6527, 0.8753, 0.48511],
+ [0.66099, 0.88562, 0.49882],
+ [0.6693, 0.89599, 0.51278],
+ [0.67763, 0.90641, 0.52699],
+ [0.68597, 0.91687, 0.54141],
+ [0.69432, 0.92738, 0.55605],
+ [0.70269, 0.93794, 0.5709],
+ [0.71107, 0.94855, 0.58593],
+ [0.71945, 0.9592, 0.60112],
+ [0.72782, 0.96989, 0.61646],
+ [0.7362, 0.98063, 0.63191],
+ [0.74458, 0.99141, 0.64748]]
+
+cmaps = {
+ name: ListedColormap(data, name=name) for name, data in [
+ ('magma', _magma_data),
+ ('inferno', _inferno_data),
+ ('plasma', _plasma_data),
+ ('viridis', _viridis_data),
+ ('cividis', _cividis_data),
+ ('twilight', _twilight_data),
+ ('twilight_shifted', _twilight_shifted_data),
+ ('turbo', _turbo_data),
+ ('berlin', _berlin_data),
+ ('managua', _managua_data),
+ ('vanimo', _vanimo_data),
+ ]}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_cm_multivar.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_cm_multivar.py
new file mode 100644
index 0000000000000000000000000000000000000000..610d7c40935b0999fe7de38515f316ce816023f7
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_cm_multivar.py
@@ -0,0 +1,166 @@
+# auto-generated by https://github.com/trygvrad/multivariate_colormaps
+# date: 2024-05-28
+
+from .colors import LinearSegmentedColormap, MultivarColormap
+import matplotlib as mpl
+_LUTSIZE = mpl.rcParams['image.lut']
+
+_2VarAddA0_data = [[0.000, 0.000, 0.000],
+ [0.020, 0.026, 0.031],
+ [0.049, 0.068, 0.085],
+ [0.075, 0.107, 0.135],
+ [0.097, 0.144, 0.183],
+ [0.116, 0.178, 0.231],
+ [0.133, 0.212, 0.279],
+ [0.148, 0.244, 0.326],
+ [0.161, 0.276, 0.374],
+ [0.173, 0.308, 0.422],
+ [0.182, 0.339, 0.471],
+ [0.190, 0.370, 0.521],
+ [0.197, 0.400, 0.572],
+ [0.201, 0.431, 0.623],
+ [0.204, 0.461, 0.675],
+ [0.204, 0.491, 0.728],
+ [0.202, 0.520, 0.783],
+ [0.197, 0.549, 0.838],
+ [0.187, 0.577, 0.895]]
+
+_2VarAddA1_data = [[0.000, 0.000, 0.000],
+ [0.030, 0.023, 0.018],
+ [0.079, 0.060, 0.043],
+ [0.125, 0.093, 0.065],
+ [0.170, 0.123, 0.083],
+ [0.213, 0.151, 0.098],
+ [0.255, 0.177, 0.110],
+ [0.298, 0.202, 0.120],
+ [0.341, 0.226, 0.128],
+ [0.384, 0.249, 0.134],
+ [0.427, 0.271, 0.138],
+ [0.472, 0.292, 0.141],
+ [0.517, 0.313, 0.142],
+ [0.563, 0.333, 0.141],
+ [0.610, 0.353, 0.139],
+ [0.658, 0.372, 0.134],
+ [0.708, 0.390, 0.127],
+ [0.759, 0.407, 0.118],
+ [0.813, 0.423, 0.105]]
+
+_2VarSubA0_data = [[1.000, 1.000, 1.000],
+ [0.959, 0.973, 0.986],
+ [0.916, 0.948, 0.974],
+ [0.874, 0.923, 0.965],
+ [0.832, 0.899, 0.956],
+ [0.790, 0.875, 0.948],
+ [0.748, 0.852, 0.940],
+ [0.707, 0.829, 0.934],
+ [0.665, 0.806, 0.927],
+ [0.624, 0.784, 0.921],
+ [0.583, 0.762, 0.916],
+ [0.541, 0.740, 0.910],
+ [0.500, 0.718, 0.905],
+ [0.457, 0.697, 0.901],
+ [0.414, 0.675, 0.896],
+ [0.369, 0.652, 0.892],
+ [0.320, 0.629, 0.888],
+ [0.266, 0.604, 0.884],
+ [0.199, 0.574, 0.881]]
+
+_2VarSubA1_data = [[1.000, 1.000, 1.000],
+ [0.982, 0.967, 0.955],
+ [0.966, 0.935, 0.908],
+ [0.951, 0.902, 0.860],
+ [0.937, 0.870, 0.813],
+ [0.923, 0.838, 0.765],
+ [0.910, 0.807, 0.718],
+ [0.898, 0.776, 0.671],
+ [0.886, 0.745, 0.624],
+ [0.874, 0.714, 0.577],
+ [0.862, 0.683, 0.530],
+ [0.851, 0.653, 0.483],
+ [0.841, 0.622, 0.435],
+ [0.831, 0.592, 0.388],
+ [0.822, 0.561, 0.340],
+ [0.813, 0.530, 0.290],
+ [0.806, 0.498, 0.239],
+ [0.802, 0.464, 0.184],
+ [0.801, 0.426, 0.119]]
+
+_3VarAddA0_data = [[0.000, 0.000, 0.000],
+ [0.018, 0.023, 0.028],
+ [0.040, 0.056, 0.071],
+ [0.059, 0.087, 0.110],
+ [0.074, 0.114, 0.147],
+ [0.086, 0.139, 0.183],
+ [0.095, 0.163, 0.219],
+ [0.101, 0.187, 0.255],
+ [0.105, 0.209, 0.290],
+ [0.107, 0.230, 0.326],
+ [0.105, 0.251, 0.362],
+ [0.101, 0.271, 0.398],
+ [0.091, 0.291, 0.434],
+ [0.075, 0.309, 0.471],
+ [0.046, 0.325, 0.507],
+ [0.021, 0.341, 0.546],
+ [0.021, 0.363, 0.584],
+ [0.022, 0.385, 0.622],
+ [0.023, 0.408, 0.661]]
+
+_3VarAddA1_data = [[0.000, 0.000, 0.000],
+ [0.020, 0.024, 0.016],
+ [0.047, 0.058, 0.034],
+ [0.072, 0.088, 0.048],
+ [0.093, 0.116, 0.059],
+ [0.113, 0.142, 0.067],
+ [0.131, 0.167, 0.071],
+ [0.149, 0.190, 0.074],
+ [0.166, 0.213, 0.074],
+ [0.182, 0.235, 0.072],
+ [0.198, 0.256, 0.068],
+ [0.215, 0.276, 0.061],
+ [0.232, 0.296, 0.051],
+ [0.249, 0.314, 0.037],
+ [0.270, 0.330, 0.018],
+ [0.288, 0.347, 0.000],
+ [0.302, 0.369, 0.000],
+ [0.315, 0.391, 0.000],
+ [0.328, 0.414, 0.000]]
+
+_3VarAddA2_data = [[0.000, 0.000, 0.000],
+ [0.029, 0.020, 0.023],
+ [0.072, 0.045, 0.055],
+ [0.111, 0.067, 0.084],
+ [0.148, 0.085, 0.109],
+ [0.184, 0.101, 0.133],
+ [0.219, 0.115, 0.155],
+ [0.254, 0.127, 0.176],
+ [0.289, 0.138, 0.195],
+ [0.323, 0.147, 0.214],
+ [0.358, 0.155, 0.232],
+ [0.393, 0.161, 0.250],
+ [0.429, 0.166, 0.267],
+ [0.467, 0.169, 0.283],
+ [0.507, 0.168, 0.298],
+ [0.546, 0.168, 0.313],
+ [0.580, 0.172, 0.328],
+ [0.615, 0.175, 0.341],
+ [0.649, 0.178, 0.355]]
+
+cmaps = {
+ name: LinearSegmentedColormap.from_list(name, data, _LUTSIZE) for name, data in [
+ ('2VarAddA0', _2VarAddA0_data),
+ ('2VarAddA1', _2VarAddA1_data),
+ ('2VarSubA0', _2VarSubA0_data),
+ ('2VarSubA1', _2VarSubA1_data),
+ ('3VarAddA0', _3VarAddA0_data),
+ ('3VarAddA1', _3VarAddA1_data),
+ ('3VarAddA2', _3VarAddA2_data),
+ ]}
+
+cmap_families = {
+ '2VarAddA': MultivarColormap([cmaps[f'2VarAddA{i}'] for i in range(2)],
+ 'sRGB_add', name='2VarAddA'),
+ '2VarSubA': MultivarColormap([cmaps[f'2VarSubA{i}'] for i in range(2)],
+ 'sRGB_sub', name='2VarSubA'),
+ '3VarAddA': MultivarColormap([cmaps[f'3VarAddA{i}'] for i in range(3)],
+ 'sRGB_add', name='3VarAddA'),
+}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_color_data.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_color_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..44f97adbb76aeaec2578cedfe60219a3278fd2ca
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_color_data.py
@@ -0,0 +1,1141 @@
+BASE_COLORS = {
+ 'b': (0, 0, 1), # blue
+ 'g': (0, 0.5, 0), # green
+ 'r': (1, 0, 0), # red
+ 'c': (0, 0.75, 0.75), # cyan
+ 'm': (0.75, 0, 0.75), # magenta
+ 'y': (0.75, 0.75, 0), # yellow
+ 'k': (0, 0, 0), # black
+ 'w': (1, 1, 1), # white
+}
+
+
+# These colors are from Tableau
+TABLEAU_COLORS = {
+ 'tab:blue': '#1f77b4',
+ 'tab:orange': '#ff7f0e',
+ 'tab:green': '#2ca02c',
+ 'tab:red': '#d62728',
+ 'tab:purple': '#9467bd',
+ 'tab:brown': '#8c564b',
+ 'tab:pink': '#e377c2',
+ 'tab:gray': '#7f7f7f',
+ 'tab:olive': '#bcbd22',
+ 'tab:cyan': '#17becf',
+}
+
+
+# This mapping of color names -> hex values is taken from
+# a survey run by Randall Munroe see:
+# https://blog.xkcd.com/2010/05/03/color-survey-results/
+# for more details. The results are hosted at
+# https://xkcd.com/color/rgb/
+# and also available as a text file at
+# https://xkcd.com/color/rgb.txt
+#
+# License: https://creativecommons.org/publicdomain/zero/1.0/
+XKCD_COLORS = {
+ 'cloudy blue': '#acc2d9',
+ 'dark pastel green': '#56ae57',
+ 'dust': '#b2996e',
+ 'electric lime': '#a8ff04',
+ 'fresh green': '#69d84f',
+ 'light eggplant': '#894585',
+ 'nasty green': '#70b23f',
+ 'really light blue': '#d4ffff',
+ 'tea': '#65ab7c',
+ 'warm purple': '#952e8f',
+ 'yellowish tan': '#fcfc81',
+ 'cement': '#a5a391',
+ 'dark grass green': '#388004',
+ 'dusty teal': '#4c9085',
+ 'grey teal': '#5e9b8a',
+ 'macaroni and cheese': '#efb435',
+ 'pinkish tan': '#d99b82',
+ 'spruce': '#0a5f38',
+ 'strong blue': '#0c06f7',
+ 'toxic green': '#61de2a',
+ 'windows blue': '#3778bf',
+ 'blue blue': '#2242c7',
+ 'blue with a hint of purple': '#533cc6',
+ 'booger': '#9bb53c',
+ 'bright sea green': '#05ffa6',
+ 'dark green blue': '#1f6357',
+ 'deep turquoise': '#017374',
+ 'green teal': '#0cb577',
+ 'strong pink': '#ff0789',
+ 'bland': '#afa88b',
+ 'deep aqua': '#08787f',
+ 'lavender pink': '#dd85d7',
+ 'light moss green': '#a6c875',
+ 'light seafoam green': '#a7ffb5',
+ 'olive yellow': '#c2b709',
+ 'pig pink': '#e78ea5',
+ 'deep lilac': '#966ebd',
+ 'desert': '#ccad60',
+ 'dusty lavender': '#ac86a8',
+ 'purpley grey': '#947e94',
+ 'purply': '#983fb2',
+ 'candy pink': '#ff63e9',
+ 'light pastel green': '#b2fba5',
+ 'boring green': '#63b365',
+ 'kiwi green': '#8ee53f',
+ 'light grey green': '#b7e1a1',
+ 'orange pink': '#ff6f52',
+ 'tea green': '#bdf8a3',
+ 'very light brown': '#d3b683',
+ 'egg shell': '#fffcc4',
+ 'eggplant purple': '#430541',
+ 'powder pink': '#ffb2d0',
+ 'reddish grey': '#997570',
+ 'baby shit brown': '#ad900d',
+ 'liliac': '#c48efd',
+ 'stormy blue': '#507b9c',
+ 'ugly brown': '#7d7103',
+ 'custard': '#fffd78',
+ 'darkish pink': '#da467d',
+ 'deep brown': '#410200',
+ 'greenish beige': '#c9d179',
+ 'manilla': '#fffa86',
+ 'off blue': '#5684ae',
+ 'battleship grey': '#6b7c85',
+ 'browny green': '#6f6c0a',
+ 'bruise': '#7e4071',
+ 'kelley green': '#009337',
+ 'sickly yellow': '#d0e429',
+ 'sunny yellow': '#fff917',
+ 'azul': '#1d5dec',
+ 'darkgreen': '#054907',
+ 'green/yellow': '#b5ce08',
+ 'lichen': '#8fb67b',
+ 'light light green': '#c8ffb0',
+ 'pale gold': '#fdde6c',
+ 'sun yellow': '#ffdf22',
+ 'tan green': '#a9be70',
+ 'burple': '#6832e3',
+ 'butterscotch': '#fdb147',
+ 'toupe': '#c7ac7d',
+ 'dark cream': '#fff39a',
+ 'indian red': '#850e04',
+ 'light lavendar': '#efc0fe',
+ 'poison green': '#40fd14',
+ 'baby puke green': '#b6c406',
+ 'bright yellow green': '#9dff00',
+ 'charcoal grey': '#3c4142',
+ 'squash': '#f2ab15',
+ 'cinnamon': '#ac4f06',
+ 'light pea green': '#c4fe82',
+ 'radioactive green': '#2cfa1f',
+ 'raw sienna': '#9a6200',
+ 'baby purple': '#ca9bf7',
+ 'cocoa': '#875f42',
+ 'light royal blue': '#3a2efe',
+ 'orangeish': '#fd8d49',
+ 'rust brown': '#8b3103',
+ 'sand brown': '#cba560',
+ 'swamp': '#698339',
+ 'tealish green': '#0cdc73',
+ 'burnt siena': '#b75203',
+ 'camo': '#7f8f4e',
+ 'dusk blue': '#26538d',
+ 'fern': '#63a950',
+ 'old rose': '#c87f89',
+ 'pale light green': '#b1fc99',
+ 'peachy pink': '#ff9a8a',
+ 'rosy pink': '#f6688e',
+ 'light bluish green': '#76fda8',
+ 'light bright green': '#53fe5c',
+ 'light neon green': '#4efd54',
+ 'light seafoam': '#a0febf',
+ 'tiffany blue': '#7bf2da',
+ 'washed out green': '#bcf5a6',
+ 'browny orange': '#ca6b02',
+ 'nice blue': '#107ab0',
+ 'sapphire': '#2138ab',
+ 'greyish teal': '#719f91',
+ 'orangey yellow': '#fdb915',
+ 'parchment': '#fefcaf',
+ 'straw': '#fcf679',
+ 'very dark brown': '#1d0200',
+ 'terracota': '#cb6843',
+ 'ugly blue': '#31668a',
+ 'clear blue': '#247afd',
+ 'creme': '#ffffb6',
+ 'foam green': '#90fda9',
+ 'grey/green': '#86a17d',
+ 'light gold': '#fddc5c',
+ 'seafoam blue': '#78d1b6',
+ 'topaz': '#13bbaf',
+ 'violet pink': '#fb5ffc',
+ 'wintergreen': '#20f986',
+ 'yellow tan': '#ffe36e',
+ 'dark fuchsia': '#9d0759',
+ 'indigo blue': '#3a18b1',
+ 'light yellowish green': '#c2ff89',
+ 'pale magenta': '#d767ad',
+ 'rich purple': '#720058',
+ 'sunflower yellow': '#ffda03',
+ 'green/blue': '#01c08d',
+ 'leather': '#ac7434',
+ 'racing green': '#014600',
+ 'vivid purple': '#9900fa',
+ 'dark royal blue': '#02066f',
+ 'hazel': '#8e7618',
+ 'muted pink': '#d1768f',
+ 'booger green': '#96b403',
+ 'canary': '#fdff63',
+ 'cool grey': '#95a3a6',
+ 'dark taupe': '#7f684e',
+ 'darkish purple': '#751973',
+ 'true green': '#089404',
+ 'coral pink': '#ff6163',
+ 'dark sage': '#598556',
+ 'dark slate blue': '#214761',
+ 'flat blue': '#3c73a8',
+ 'mushroom': '#ba9e88',
+ 'rich blue': '#021bf9',
+ 'dirty purple': '#734a65',
+ 'greenblue': '#23c48b',
+ 'icky green': '#8fae22',
+ 'light khaki': '#e6f2a2',
+ 'warm blue': '#4b57db',
+ 'dark hot pink': '#d90166',
+ 'deep sea blue': '#015482',
+ 'carmine': '#9d0216',
+ 'dark yellow green': '#728f02',
+ 'pale peach': '#ffe5ad',
+ 'plum purple': '#4e0550',
+ 'golden rod': '#f9bc08',
+ 'neon red': '#ff073a',
+ 'old pink': '#c77986',
+ 'very pale blue': '#d6fffe',
+ 'blood orange': '#fe4b03',
+ 'grapefruit': '#fd5956',
+ 'sand yellow': '#fce166',
+ 'clay brown': '#b2713d',
+ 'dark blue grey': '#1f3b4d',
+ 'flat green': '#699d4c',
+ 'light green blue': '#56fca2',
+ 'warm pink': '#fb5581',
+ 'dodger blue': '#3e82fc',
+ 'gross green': '#a0bf16',
+ 'ice': '#d6fffa',
+ 'metallic blue': '#4f738e',
+ 'pale salmon': '#ffb19a',
+ 'sap green': '#5c8b15',
+ 'algae': '#54ac68',
+ 'bluey grey': '#89a0b0',
+ 'greeny grey': '#7ea07a',
+ 'highlighter green': '#1bfc06',
+ 'light light blue': '#cafffb',
+ 'light mint': '#b6ffbb',
+ 'raw umber': '#a75e09',
+ 'vivid blue': '#152eff',
+ 'deep lavender': '#8d5eb7',
+ 'dull teal': '#5f9e8f',
+ 'light greenish blue': '#63f7b4',
+ 'mud green': '#606602',
+ 'pinky': '#fc86aa',
+ 'red wine': '#8c0034',
+ 'shit green': '#758000',
+ 'tan brown': '#ab7e4c',
+ 'darkblue': '#030764',
+ 'rosa': '#fe86a4',
+ 'lipstick': '#d5174e',
+ 'pale mauve': '#fed0fc',
+ 'claret': '#680018',
+ 'dandelion': '#fedf08',
+ 'orangered': '#fe420f',
+ 'poop green': '#6f7c00',
+ 'ruby': '#ca0147',
+ 'dark': '#1b2431',
+ 'greenish turquoise': '#00fbb0',
+ 'pastel red': '#db5856',
+ 'piss yellow': '#ddd618',
+ 'bright cyan': '#41fdfe',
+ 'dark coral': '#cf524e',
+ 'algae green': '#21c36f',
+ 'darkish red': '#a90308',
+ 'reddy brown': '#6e1005',
+ 'blush pink': '#fe828c',
+ 'camouflage green': '#4b6113',
+ 'lawn green': '#4da409',
+ 'putty': '#beae8a',
+ 'vibrant blue': '#0339f8',
+ 'dark sand': '#a88f59',
+ 'purple/blue': '#5d21d0',
+ 'saffron': '#feb209',
+ 'twilight': '#4e518b',
+ 'warm brown': '#964e02',
+ 'bluegrey': '#85a3b2',
+ 'bubble gum pink': '#ff69af',
+ 'duck egg blue': '#c3fbf4',
+ 'greenish cyan': '#2afeb7',
+ 'petrol': '#005f6a',
+ 'royal': '#0c1793',
+ 'butter': '#ffff81',
+ 'dusty orange': '#f0833a',
+ 'off yellow': '#f1f33f',
+ 'pale olive green': '#b1d27b',
+ 'orangish': '#fc824a',
+ 'leaf': '#71aa34',
+ 'light blue grey': '#b7c9e2',
+ 'dried blood': '#4b0101',
+ 'lightish purple': '#a552e6',
+ 'rusty red': '#af2f0d',
+ 'lavender blue': '#8b88f8',
+ 'light grass green': '#9af764',
+ 'light mint green': '#a6fbb2',
+ 'sunflower': '#ffc512',
+ 'velvet': '#750851',
+ 'brick orange': '#c14a09',
+ 'lightish red': '#fe2f4a',
+ 'pure blue': '#0203e2',
+ 'twilight blue': '#0a437a',
+ 'violet red': '#a50055',
+ 'yellowy brown': '#ae8b0c',
+ 'carnation': '#fd798f',
+ 'muddy yellow': '#bfac05',
+ 'dark seafoam green': '#3eaf76',
+ 'deep rose': '#c74767',
+ 'dusty red': '#b9484e',
+ 'grey/blue': '#647d8e',
+ 'lemon lime': '#bffe28',
+ 'purple/pink': '#d725de',
+ 'brown yellow': '#b29705',
+ 'purple brown': '#673a3f',
+ 'wisteria': '#a87dc2',
+ 'banana yellow': '#fafe4b',
+ 'lipstick red': '#c0022f',
+ 'water blue': '#0e87cc',
+ 'brown grey': '#8d8468',
+ 'vibrant purple': '#ad03de',
+ 'baby green': '#8cff9e',
+ 'barf green': '#94ac02',
+ 'eggshell blue': '#c4fff7',
+ 'sandy yellow': '#fdee73',
+ 'cool green': '#33b864',
+ 'pale': '#fff9d0',
+ 'blue/grey': '#758da3',
+ 'hot magenta': '#f504c9',
+ 'greyblue': '#77a1b5',
+ 'purpley': '#8756e4',
+ 'baby shit green': '#889717',
+ 'brownish pink': '#c27e79',
+ 'dark aquamarine': '#017371',
+ 'diarrhea': '#9f8303',
+ 'light mustard': '#f7d560',
+ 'pale sky blue': '#bdf6fe',
+ 'turtle green': '#75b84f',
+ 'bright olive': '#9cbb04',
+ 'dark grey blue': '#29465b',
+ 'greeny brown': '#696006',
+ 'lemon green': '#adf802',
+ 'light periwinkle': '#c1c6fc',
+ 'seaweed green': '#35ad6b',
+ 'sunshine yellow': '#fffd37',
+ 'ugly purple': '#a442a0',
+ 'medium pink': '#f36196',
+ 'puke brown': '#947706',
+ 'very light pink': '#fff4f2',
+ 'viridian': '#1e9167',
+ 'bile': '#b5c306',
+ 'faded yellow': '#feff7f',
+ 'very pale green': '#cffdbc',
+ 'vibrant green': '#0add08',
+ 'bright lime': '#87fd05',
+ 'spearmint': '#1ef876',
+ 'light aquamarine': '#7bfdc7',
+ 'light sage': '#bcecac',
+ 'yellowgreen': '#bbf90f',
+ 'baby poo': '#ab9004',
+ 'dark seafoam': '#1fb57a',
+ 'deep teal': '#00555a',
+ 'heather': '#a484ac',
+ 'rust orange': '#c45508',
+ 'dirty blue': '#3f829d',
+ 'fern green': '#548d44',
+ 'bright lilac': '#c95efb',
+ 'weird green': '#3ae57f',
+ 'peacock blue': '#016795',
+ 'avocado green': '#87a922',
+ 'faded orange': '#f0944d',
+ 'grape purple': '#5d1451',
+ 'hot green': '#25ff29',
+ 'lime yellow': '#d0fe1d',
+ 'mango': '#ffa62b',
+ 'shamrock': '#01b44c',
+ 'bubblegum': '#ff6cb5',
+ 'purplish brown': '#6b4247',
+ 'vomit yellow': '#c7c10c',
+ 'pale cyan': '#b7fffa',
+ 'key lime': '#aeff6e',
+ 'tomato red': '#ec2d01',
+ 'lightgreen': '#76ff7b',
+ 'merlot': '#730039',
+ 'night blue': '#040348',
+ 'purpleish pink': '#df4ec8',
+ 'apple': '#6ecb3c',
+ 'baby poop green': '#8f9805',
+ 'green apple': '#5edc1f',
+ 'heliotrope': '#d94ff5',
+ 'yellow/green': '#c8fd3d',
+ 'almost black': '#070d0d',
+ 'cool blue': '#4984b8',
+ 'leafy green': '#51b73b',
+ 'mustard brown': '#ac7e04',
+ 'dusk': '#4e5481',
+ 'dull brown': '#876e4b',
+ 'frog green': '#58bc08',
+ 'vivid green': '#2fef10',
+ 'bright light green': '#2dfe54',
+ 'fluro green': '#0aff02',
+ 'kiwi': '#9cef43',
+ 'seaweed': '#18d17b',
+ 'navy green': '#35530a',
+ 'ultramarine blue': '#1805db',
+ 'iris': '#6258c4',
+ 'pastel orange': '#ff964f',
+ 'yellowish orange': '#ffab0f',
+ 'perrywinkle': '#8f8ce7',
+ 'tealish': '#24bca8',
+ 'dark plum': '#3f012c',
+ 'pear': '#cbf85f',
+ 'pinkish orange': '#ff724c',
+ 'midnight purple': '#280137',
+ 'light urple': '#b36ff6',
+ 'dark mint': '#48c072',
+ 'greenish tan': '#bccb7a',
+ 'light burgundy': '#a8415b',
+ 'turquoise blue': '#06b1c4',
+ 'ugly pink': '#cd7584',
+ 'sandy': '#f1da7a',
+ 'electric pink': '#ff0490',
+ 'muted purple': '#805b87',
+ 'mid green': '#50a747',
+ 'greyish': '#a8a495',
+ 'neon yellow': '#cfff04',
+ 'banana': '#ffff7e',
+ 'carnation pink': '#ff7fa7',
+ 'tomato': '#ef4026',
+ 'sea': '#3c9992',
+ 'muddy brown': '#886806',
+ 'turquoise green': '#04f489',
+ 'buff': '#fef69e',
+ 'fawn': '#cfaf7b',
+ 'muted blue': '#3b719f',
+ 'pale rose': '#fdc1c5',
+ 'dark mint green': '#20c073',
+ 'amethyst': '#9b5fc0',
+ 'blue/green': '#0f9b8e',
+ 'chestnut': '#742802',
+ 'sick green': '#9db92c',
+ 'pea': '#a4bf20',
+ 'rusty orange': '#cd5909',
+ 'stone': '#ada587',
+ 'rose red': '#be013c',
+ 'pale aqua': '#b8ffeb',
+ 'deep orange': '#dc4d01',
+ 'earth': '#a2653e',
+ 'mossy green': '#638b27',
+ 'grassy green': '#419c03',
+ 'pale lime green': '#b1ff65',
+ 'light grey blue': '#9dbcd4',
+ 'pale grey': '#fdfdfe',
+ 'asparagus': '#77ab56',
+ 'blueberry': '#464196',
+ 'purple red': '#990147',
+ 'pale lime': '#befd73',
+ 'greenish teal': '#32bf84',
+ 'caramel': '#af6f09',
+ 'deep magenta': '#a0025c',
+ 'light peach': '#ffd8b1',
+ 'milk chocolate': '#7f4e1e',
+ 'ocher': '#bf9b0c',
+ 'off green': '#6ba353',
+ 'purply pink': '#f075e6',
+ 'lightblue': '#7bc8f6',
+ 'dusky blue': '#475f94',
+ 'golden': '#f5bf03',
+ 'light beige': '#fffeb6',
+ 'butter yellow': '#fffd74',
+ 'dusky purple': '#895b7b',
+ 'french blue': '#436bad',
+ 'ugly yellow': '#d0c101',
+ 'greeny yellow': '#c6f808',
+ 'orangish red': '#f43605',
+ 'shamrock green': '#02c14d',
+ 'orangish brown': '#b25f03',
+ 'tree green': '#2a7e19',
+ 'deep violet': '#490648',
+ 'gunmetal': '#536267',
+ 'blue/purple': '#5a06ef',
+ 'cherry': '#cf0234',
+ 'sandy brown': '#c4a661',
+ 'warm grey': '#978a84',
+ 'dark indigo': '#1f0954',
+ 'midnight': '#03012d',
+ 'bluey green': '#2bb179',
+ 'grey pink': '#c3909b',
+ 'soft purple': '#a66fb5',
+ 'blood': '#770001',
+ 'brown red': '#922b05',
+ 'medium grey': '#7d7f7c',
+ 'berry': '#990f4b',
+ 'poo': '#8f7303',
+ 'purpley pink': '#c83cb9',
+ 'light salmon': '#fea993',
+ 'snot': '#acbb0d',
+ 'easter purple': '#c071fe',
+ 'light yellow green': '#ccfd7f',
+ 'dark navy blue': '#00022e',
+ 'drab': '#828344',
+ 'light rose': '#ffc5cb',
+ 'rouge': '#ab1239',
+ 'purplish red': '#b0054b',
+ 'slime green': '#99cc04',
+ 'baby poop': '#937c00',
+ 'irish green': '#019529',
+ 'pink/purple': '#ef1de7',
+ 'dark navy': '#000435',
+ 'greeny blue': '#42b395',
+ 'light plum': '#9d5783',
+ 'pinkish grey': '#c8aca9',
+ 'dirty orange': '#c87606',
+ 'rust red': '#aa2704',
+ 'pale lilac': '#e4cbff',
+ 'orangey red': '#fa4224',
+ 'primary blue': '#0804f9',
+ 'kermit green': '#5cb200',
+ 'brownish purple': '#76424e',
+ 'murky green': '#6c7a0e',
+ 'wheat': '#fbdd7e',
+ 'very dark purple': '#2a0134',
+ 'bottle green': '#044a05',
+ 'watermelon': '#fd4659',
+ 'deep sky blue': '#0d75f8',
+ 'fire engine red': '#fe0002',
+ 'yellow ochre': '#cb9d06',
+ 'pumpkin orange': '#fb7d07',
+ 'pale olive': '#b9cc81',
+ 'light lilac': '#edc8ff',
+ 'lightish green': '#61e160',
+ 'carolina blue': '#8ab8fe',
+ 'mulberry': '#920a4e',
+ 'shocking pink': '#fe02a2',
+ 'auburn': '#9a3001',
+ 'bright lime green': '#65fe08',
+ 'celadon': '#befdb7',
+ 'pinkish brown': '#b17261',
+ 'poo brown': '#885f01',
+ 'bright sky blue': '#02ccfe',
+ 'celery': '#c1fd95',
+ 'dirt brown': '#836539',
+ 'strawberry': '#fb2943',
+ 'dark lime': '#84b701',
+ 'copper': '#b66325',
+ 'medium brown': '#7f5112',
+ 'muted green': '#5fa052',
+ "robin's egg": '#6dedfd',
+ 'bright aqua': '#0bf9ea',
+ 'bright lavender': '#c760ff',
+ 'ivory': '#ffffcb',
+ 'very light purple': '#f6cefc',
+ 'light navy': '#155084',
+ 'pink red': '#f5054f',
+ 'olive brown': '#645403',
+ 'poop brown': '#7a5901',
+ 'mustard green': '#a8b504',
+ 'ocean green': '#3d9973',
+ 'very dark blue': '#000133',
+ 'dusty green': '#76a973',
+ 'light navy blue': '#2e5a88',
+ 'minty green': '#0bf77d',
+ 'adobe': '#bd6c48',
+ 'barney': '#ac1db8',
+ 'jade green': '#2baf6a',
+ 'bright light blue': '#26f7fd',
+ 'light lime': '#aefd6c',
+ 'dark khaki': '#9b8f55',
+ 'orange yellow': '#ffad01',
+ 'ocre': '#c69c04',
+ 'maize': '#f4d054',
+ 'faded pink': '#de9dac',
+ 'british racing green': '#05480d',
+ 'sandstone': '#c9ae74',
+ 'mud brown': '#60460f',
+ 'light sea green': '#98f6b0',
+ 'robin egg blue': '#8af1fe',
+ 'aqua marine': '#2ee8bb',
+ 'dark sea green': '#11875d',
+ 'soft pink': '#fdb0c0',
+ 'orangey brown': '#b16002',
+ 'cherry red': '#f7022a',
+ 'burnt yellow': '#d5ab09',
+ 'brownish grey': '#86775f',
+ 'camel': '#c69f59',
+ 'purplish grey': '#7a687f',
+ 'marine': '#042e60',
+ 'greyish pink': '#c88d94',
+ 'pale turquoise': '#a5fbd5',
+ 'pastel yellow': '#fffe71',
+ 'bluey purple': '#6241c7',
+ 'canary yellow': '#fffe40',
+ 'faded red': '#d3494e',
+ 'sepia': '#985e2b',
+ 'coffee': '#a6814c',
+ 'bright magenta': '#ff08e8',
+ 'mocha': '#9d7651',
+ 'ecru': '#feffca',
+ 'purpleish': '#98568d',
+ 'cranberry': '#9e003a',
+ 'darkish green': '#287c37',
+ 'brown orange': '#b96902',
+ 'dusky rose': '#ba6873',
+ 'melon': '#ff7855',
+ 'sickly green': '#94b21c',
+ 'silver': '#c5c9c7',
+ 'purply blue': '#661aee',
+ 'purpleish blue': '#6140ef',
+ 'hospital green': '#9be5aa',
+ 'shit brown': '#7b5804',
+ 'mid blue': '#276ab3',
+ 'amber': '#feb308',
+ 'easter green': '#8cfd7e',
+ 'soft blue': '#6488ea',
+ 'cerulean blue': '#056eee',
+ 'golden brown': '#b27a01',
+ 'bright turquoise': '#0ffef9',
+ 'red pink': '#fa2a55',
+ 'red purple': '#820747',
+ 'greyish brown': '#7a6a4f',
+ 'vermillion': '#f4320c',
+ 'russet': '#a13905',
+ 'steel grey': '#6f828a',
+ 'lighter purple': '#a55af4',
+ 'bright violet': '#ad0afd',
+ 'prussian blue': '#004577',
+ 'slate green': '#658d6d',
+ 'dirty pink': '#ca7b80',
+ 'dark blue green': '#005249',
+ 'pine': '#2b5d34',
+ 'yellowy green': '#bff128',
+ 'dark gold': '#b59410',
+ 'bluish': '#2976bb',
+ 'darkish blue': '#014182',
+ 'dull red': '#bb3f3f',
+ 'pinky red': '#fc2647',
+ 'bronze': '#a87900',
+ 'pale teal': '#82cbb2',
+ 'military green': '#667c3e',
+ 'barbie pink': '#fe46a5',
+ 'bubblegum pink': '#fe83cc',
+ 'pea soup green': '#94a617',
+ 'dark mustard': '#a88905',
+ 'shit': '#7f5f00',
+ 'medium purple': '#9e43a2',
+ 'very dark green': '#062e03',
+ 'dirt': '#8a6e45',
+ 'dusky pink': '#cc7a8b',
+ 'red violet': '#9e0168',
+ 'lemon yellow': '#fdff38',
+ 'pistachio': '#c0fa8b',
+ 'dull yellow': '#eedc5b',
+ 'dark lime green': '#7ebd01',
+ 'denim blue': '#3b5b92',
+ 'teal blue': '#01889f',
+ 'lightish blue': '#3d7afd',
+ 'purpley blue': '#5f34e7',
+ 'light indigo': '#6d5acf',
+ 'swamp green': '#748500',
+ 'brown green': '#706c11',
+ 'dark maroon': '#3c0008',
+ 'hot purple': '#cb00f5',
+ 'dark forest green': '#002d04',
+ 'faded blue': '#658cbb',
+ 'drab green': '#749551',
+ 'light lime green': '#b9ff66',
+ 'snot green': '#9dc100',
+ 'yellowish': '#faee66',
+ 'light blue green': '#7efbb3',
+ 'bordeaux': '#7b002c',
+ 'light mauve': '#c292a1',
+ 'ocean': '#017b92',
+ 'marigold': '#fcc006',
+ 'muddy green': '#657432',
+ 'dull orange': '#d8863b',
+ 'steel': '#738595',
+ 'electric purple': '#aa23ff',
+ 'fluorescent green': '#08ff08',
+ 'yellowish brown': '#9b7a01',
+ 'blush': '#f29e8e',
+ 'soft green': '#6fc276',
+ 'bright orange': '#ff5b00',
+ 'lemon': '#fdff52',
+ 'purple grey': '#866f85',
+ 'acid green': '#8ffe09',
+ 'pale lavender': '#eecffe',
+ 'violet blue': '#510ac9',
+ 'light forest green': '#4f9153',
+ 'burnt red': '#9f2305',
+ 'khaki green': '#728639',
+ 'cerise': '#de0c62',
+ 'faded purple': '#916e99',
+ 'apricot': '#ffb16d',
+ 'dark olive green': '#3c4d03',
+ 'grey brown': '#7f7053',
+ 'green grey': '#77926f',
+ 'true blue': '#010fcc',
+ 'pale violet': '#ceaefa',
+ 'periwinkle blue': '#8f99fb',
+ 'light sky blue': '#c6fcff',
+ 'blurple': '#5539cc',
+ 'green brown': '#544e03',
+ 'bluegreen': '#017a79',
+ 'bright teal': '#01f9c6',
+ 'brownish yellow': '#c9b003',
+ 'pea soup': '#929901',
+ 'forest': '#0b5509',
+ 'barney purple': '#a00498',
+ 'ultramarine': '#2000b1',
+ 'purplish': '#94568c',
+ 'puke yellow': '#c2be0e',
+ 'bluish grey': '#748b97',
+ 'dark periwinkle': '#665fd1',
+ 'dark lilac': '#9c6da5',
+ 'reddish': '#c44240',
+ 'light maroon': '#a24857',
+ 'dusty purple': '#825f87',
+ 'terra cotta': '#c9643b',
+ 'avocado': '#90b134',
+ 'marine blue': '#01386a',
+ 'teal green': '#25a36f',
+ 'slate grey': '#59656d',
+ 'lighter green': '#75fd63',
+ 'electric green': '#21fc0d',
+ 'dusty blue': '#5a86ad',
+ 'golden yellow': '#fec615',
+ 'bright yellow': '#fffd01',
+ 'light lavender': '#dfc5fe',
+ 'umber': '#b26400',
+ 'poop': '#7f5e00',
+ 'dark peach': '#de7e5d',
+ 'jungle green': '#048243',
+ 'eggshell': '#ffffd4',
+ 'denim': '#3b638c',
+ 'yellow brown': '#b79400',
+ 'dull purple': '#84597e',
+ 'chocolate brown': '#411900',
+ 'wine red': '#7b0323',
+ 'neon blue': '#04d9ff',
+ 'dirty green': '#667e2c',
+ 'light tan': '#fbeeac',
+ 'ice blue': '#d7fffe',
+ 'cadet blue': '#4e7496',
+ 'dark mauve': '#874c62',
+ 'very light blue': '#d5ffff',
+ 'grey purple': '#826d8c',
+ 'pastel pink': '#ffbacd',
+ 'very light green': '#d1ffbd',
+ 'dark sky blue': '#448ee4',
+ 'evergreen': '#05472a',
+ 'dull pink': '#d5869d',
+ 'aubergine': '#3d0734',
+ 'mahogany': '#4a0100',
+ 'reddish orange': '#f8481c',
+ 'deep green': '#02590f',
+ 'vomit green': '#89a203',
+ 'purple pink': '#e03fd8',
+ 'dusty pink': '#d58a94',
+ 'faded green': '#7bb274',
+ 'camo green': '#526525',
+ 'pinky purple': '#c94cbe',
+ 'pink purple': '#db4bda',
+ 'brownish red': '#9e3623',
+ 'dark rose': '#b5485d',
+ 'mud': '#735c12',
+ 'brownish': '#9c6d57',
+ 'emerald green': '#028f1e',
+ 'pale brown': '#b1916e',
+ 'dull blue': '#49759c',
+ 'burnt umber': '#a0450e',
+ 'medium green': '#39ad48',
+ 'clay': '#b66a50',
+ 'light aqua': '#8cffdb',
+ 'light olive green': '#a4be5c',
+ 'brownish orange': '#cb7723',
+ 'dark aqua': '#05696b',
+ 'purplish pink': '#ce5dae',
+ 'dark salmon': '#c85a53',
+ 'greenish grey': '#96ae8d',
+ 'jade': '#1fa774',
+ 'ugly green': '#7a9703',
+ 'dark beige': '#ac9362',
+ 'emerald': '#01a049',
+ 'pale red': '#d9544d',
+ 'light magenta': '#fa5ff7',
+ 'sky': '#82cafc',
+ 'light cyan': '#acfffc',
+ 'yellow orange': '#fcb001',
+ 'reddish purple': '#910951',
+ 'reddish pink': '#fe2c54',
+ 'orchid': '#c875c4',
+ 'dirty yellow': '#cdc50a',
+ 'orange red': '#fd411e',
+ 'deep red': '#9a0200',
+ 'orange brown': '#be6400',
+ 'cobalt blue': '#030aa7',
+ 'neon pink': '#fe019a',
+ 'rose pink': '#f7879a',
+ 'greyish purple': '#887191',
+ 'raspberry': '#b00149',
+ 'aqua green': '#12e193',
+ 'salmon pink': '#fe7b7c',
+ 'tangerine': '#ff9408',
+ 'brownish green': '#6a6e09',
+ 'red brown': '#8b2e16',
+ 'greenish brown': '#696112',
+ 'pumpkin': '#e17701',
+ 'pine green': '#0a481e',
+ 'charcoal': '#343837',
+ 'baby pink': '#ffb7ce',
+ 'cornflower': '#6a79f7',
+ 'blue violet': '#5d06e9',
+ 'chocolate': '#3d1c02',
+ 'greyish green': '#82a67d',
+ 'scarlet': '#be0119',
+ 'green yellow': '#c9ff27',
+ 'dark olive': '#373e02',
+ 'sienna': '#a9561e',
+ 'pastel purple': '#caa0ff',
+ 'terracotta': '#ca6641',
+ 'aqua blue': '#02d8e9',
+ 'sage green': '#88b378',
+ 'blood red': '#980002',
+ 'deep pink': '#cb0162',
+ 'grass': '#5cac2d',
+ 'moss': '#769958',
+ 'pastel blue': '#a2bffe',
+ 'bluish green': '#10a674',
+ 'green blue': '#06b48b',
+ 'dark tan': '#af884a',
+ 'greenish blue': '#0b8b87',
+ 'pale orange': '#ffa756',
+ 'vomit': '#a2a415',
+ 'forrest green': '#154406',
+ 'dark lavender': '#856798',
+ 'dark violet': '#34013f',
+ 'purple blue': '#632de9',
+ 'dark cyan': '#0a888a',
+ 'olive drab': '#6f7632',
+ 'pinkish': '#d46a7e',
+ 'cobalt': '#1e488f',
+ 'neon purple': '#bc13fe',
+ 'light turquoise': '#7ef4cc',
+ 'apple green': '#76cd26',
+ 'dull green': '#74a662',
+ 'wine': '#80013f',
+ 'powder blue': '#b1d1fc',
+ 'off white': '#ffffe4',
+ 'electric blue': '#0652ff',
+ 'dark turquoise': '#045c5a',
+ 'blue purple': '#5729ce',
+ 'azure': '#069af3',
+ 'bright red': '#ff000d',
+ 'pinkish red': '#f10c45',
+ 'cornflower blue': '#5170d7',
+ 'light olive': '#acbf69',
+ 'grape': '#6c3461',
+ 'greyish blue': '#5e819d',
+ 'purplish blue': '#601ef9',
+ 'yellowish green': '#b0dd16',
+ 'greenish yellow': '#cdfd02',
+ 'medium blue': '#2c6fbb',
+ 'dusty rose': '#c0737a',
+ 'light violet': '#d6b4fc',
+ 'midnight blue': '#020035',
+ 'bluish purple': '#703be7',
+ 'red orange': '#fd3c06',
+ 'dark magenta': '#960056',
+ 'greenish': '#40a368',
+ 'ocean blue': '#03719c',
+ 'coral': '#fc5a50',
+ 'cream': '#ffffc2',
+ 'reddish brown': '#7f2b0a',
+ 'burnt sienna': '#b04e0f',
+ 'brick': '#a03623',
+ 'sage': '#87ae73',
+ 'grey green': '#789b73',
+ 'white': '#ffffff',
+ "robin's egg blue": '#98eff9',
+ 'moss green': '#658b38',
+ 'steel blue': '#5a7d9a',
+ 'eggplant': '#380835',
+ 'light yellow': '#fffe7a',
+ 'leaf green': '#5ca904',
+ 'light grey': '#d8dcd6',
+ 'puke': '#a5a502',
+ 'pinkish purple': '#d648d7',
+ 'sea blue': '#047495',
+ 'pale purple': '#b790d4',
+ 'slate blue': '#5b7c99',
+ 'blue grey': '#607c8e',
+ 'hunter green': '#0b4008',
+ 'fuchsia': '#ed0dd9',
+ 'crimson': '#8c000f',
+ 'pale yellow': '#ffff84',
+ 'ochre': '#bf9005',
+ 'mustard yellow': '#d2bd0a',
+ 'light red': '#ff474c',
+ 'cerulean': '#0485d1',
+ 'pale pink': '#ffcfdc',
+ 'deep blue': '#040273',
+ 'rust': '#a83c09',
+ 'light teal': '#90e4c1',
+ 'slate': '#516572',
+ 'goldenrod': '#fac205',
+ 'dark yellow': '#d5b60a',
+ 'dark grey': '#363737',
+ 'army green': '#4b5d16',
+ 'grey blue': '#6b8ba4',
+ 'seafoam': '#80f9ad',
+ 'puce': '#a57e52',
+ 'spring green': '#a9f971',
+ 'dark orange': '#c65102',
+ 'sand': '#e2ca76',
+ 'pastel green': '#b0ff9d',
+ 'mint': '#9ffeb0',
+ 'light orange': '#fdaa48',
+ 'bright pink': '#fe01b1',
+ 'chartreuse': '#c1f80a',
+ 'deep purple': '#36013f',
+ 'dark brown': '#341c02',
+ 'taupe': '#b9a281',
+ 'pea green': '#8eab12',
+ 'puke green': '#9aae07',
+ 'kelly green': '#02ab2e',
+ 'seafoam green': '#7af9ab',
+ 'blue green': '#137e6d',
+ 'khaki': '#aaa662',
+ 'burgundy': '#610023',
+ 'dark teal': '#014d4e',
+ 'brick red': '#8f1402',
+ 'royal purple': '#4b006e',
+ 'plum': '#580f41',
+ 'mint green': '#8fff9f',
+ 'gold': '#dbb40c',
+ 'baby blue': '#a2cffe',
+ 'yellow green': '#c0fb2d',
+ 'bright purple': '#be03fd',
+ 'dark red': '#840000',
+ 'pale blue': '#d0fefe',
+ 'grass green': '#3f9b0b',
+ 'navy': '#01153e',
+ 'aquamarine': '#04d8b2',
+ 'burnt orange': '#c04e01',
+ 'neon green': '#0cff0c',
+ 'bright blue': '#0165fc',
+ 'rose': '#cf6275',
+ 'light pink': '#ffd1df',
+ 'mustard': '#ceb301',
+ 'indigo': '#380282',
+ 'lime': '#aaff32',
+ 'sea green': '#53fca1',
+ 'periwinkle': '#8e82fe',
+ 'dark pink': '#cb416b',
+ 'olive green': '#677a04',
+ 'peach': '#ffb07c',
+ 'pale green': '#c7fdb5',
+ 'light brown': '#ad8150',
+ 'hot pink': '#ff028d',
+ 'black': '#000000',
+ 'lilac': '#cea2fd',
+ 'navy blue': '#001146',
+ 'royal blue': '#0504aa',
+ 'beige': '#e6daa6',
+ 'salmon': '#ff796c',
+ 'olive': '#6e750e',
+ 'maroon': '#650021',
+ 'bright green': '#01ff07',
+ 'dark purple': '#35063e',
+ 'mauve': '#ae7181',
+ 'forest green': '#06470c',
+ 'aqua': '#13eac9',
+ 'cyan': '#00ffff',
+ 'tan': '#d1b26f',
+ 'dark blue': '#00035b',
+ 'lavender': '#c79fef',
+ 'turquoise': '#06c2ac',
+ 'dark green': '#033500',
+ 'violet': '#9a0eea',
+ 'light purple': '#bf77f6',
+ 'lime green': '#89fe05',
+ 'grey': '#929591',
+ 'sky blue': '#75bbfd',
+ 'yellow': '#ffff14',
+ 'magenta': '#c20078',
+ 'light green': '#96f97b',
+ 'orange': '#f97306',
+ 'teal': '#029386',
+ 'light blue': '#95d0fc',
+ 'red': '#e50000',
+ 'brown': '#653700',
+ 'pink': '#ff81c0',
+ 'blue': '#0343df',
+ 'green': '#15b01a',
+ 'purple': '#7e1e9c'}
+
+# Normalize name to "xkcd:" to avoid name collisions.
+XKCD_COLORS = {'xkcd:' + name: value for name, value in XKCD_COLORS.items()}
+
+
+# https://drafts.csswg.org/css-color-4/#named-colors
+CSS4_COLORS = {
+ 'aliceblue': '#F0F8FF',
+ 'antiquewhite': '#FAEBD7',
+ 'aqua': '#00FFFF',
+ 'aquamarine': '#7FFFD4',
+ 'azure': '#F0FFFF',
+ 'beige': '#F5F5DC',
+ 'bisque': '#FFE4C4',
+ 'black': '#000000',
+ 'blanchedalmond': '#FFEBCD',
+ 'blue': '#0000FF',
+ 'blueviolet': '#8A2BE2',
+ 'brown': '#A52A2A',
+ 'burlywood': '#DEB887',
+ 'cadetblue': '#5F9EA0',
+ 'chartreuse': '#7FFF00',
+ 'chocolate': '#D2691E',
+ 'coral': '#FF7F50',
+ 'cornflowerblue': '#6495ED',
+ 'cornsilk': '#FFF8DC',
+ 'crimson': '#DC143C',
+ 'cyan': '#00FFFF',
+ 'darkblue': '#00008B',
+ 'darkcyan': '#008B8B',
+ 'darkgoldenrod': '#B8860B',
+ 'darkgray': '#A9A9A9',
+ 'darkgreen': '#006400',
+ 'darkgrey': '#A9A9A9',
+ 'darkkhaki': '#BDB76B',
+ 'darkmagenta': '#8B008B',
+ 'darkolivegreen': '#556B2F',
+ 'darkorange': '#FF8C00',
+ 'darkorchid': '#9932CC',
+ 'darkred': '#8B0000',
+ 'darksalmon': '#E9967A',
+ 'darkseagreen': '#8FBC8F',
+ 'darkslateblue': '#483D8B',
+ 'darkslategray': '#2F4F4F',
+ 'darkslategrey': '#2F4F4F',
+ 'darkturquoise': '#00CED1',
+ 'darkviolet': '#9400D3',
+ 'deeppink': '#FF1493',
+ 'deepskyblue': '#00BFFF',
+ 'dimgray': '#696969',
+ 'dimgrey': '#696969',
+ 'dodgerblue': '#1E90FF',
+ 'firebrick': '#B22222',
+ 'floralwhite': '#FFFAF0',
+ 'forestgreen': '#228B22',
+ 'fuchsia': '#FF00FF',
+ 'gainsboro': '#DCDCDC',
+ 'ghostwhite': '#F8F8FF',
+ 'gold': '#FFD700',
+ 'goldenrod': '#DAA520',
+ 'gray': '#808080',
+ 'green': '#008000',
+ 'greenyellow': '#ADFF2F',
+ 'grey': '#808080',
+ 'honeydew': '#F0FFF0',
+ 'hotpink': '#FF69B4',
+ 'indianred': '#CD5C5C',
+ 'indigo': '#4B0082',
+ 'ivory': '#FFFFF0',
+ 'khaki': '#F0E68C',
+ 'lavender': '#E6E6FA',
+ 'lavenderblush': '#FFF0F5',
+ 'lawngreen': '#7CFC00',
+ 'lemonchiffon': '#FFFACD',
+ 'lightblue': '#ADD8E6',
+ 'lightcoral': '#F08080',
+ 'lightcyan': '#E0FFFF',
+ 'lightgoldenrodyellow': '#FAFAD2',
+ 'lightgray': '#D3D3D3',
+ 'lightgreen': '#90EE90',
+ 'lightgrey': '#D3D3D3',
+ 'lightpink': '#FFB6C1',
+ 'lightsalmon': '#FFA07A',
+ 'lightseagreen': '#20B2AA',
+ 'lightskyblue': '#87CEFA',
+ 'lightslategray': '#778899',
+ 'lightslategrey': '#778899',
+ 'lightsteelblue': '#B0C4DE',
+ 'lightyellow': '#FFFFE0',
+ 'lime': '#00FF00',
+ 'limegreen': '#32CD32',
+ 'linen': '#FAF0E6',
+ 'magenta': '#FF00FF',
+ 'maroon': '#800000',
+ 'mediumaquamarine': '#66CDAA',
+ 'mediumblue': '#0000CD',
+ 'mediumorchid': '#BA55D3',
+ 'mediumpurple': '#9370DB',
+ 'mediumseagreen': '#3CB371',
+ 'mediumslateblue': '#7B68EE',
+ 'mediumspringgreen': '#00FA9A',
+ 'mediumturquoise': '#48D1CC',
+ 'mediumvioletred': '#C71585',
+ 'midnightblue': '#191970',
+ 'mintcream': '#F5FFFA',
+ 'mistyrose': '#FFE4E1',
+ 'moccasin': '#FFE4B5',
+ 'navajowhite': '#FFDEAD',
+ 'navy': '#000080',
+ 'oldlace': '#FDF5E6',
+ 'olive': '#808000',
+ 'olivedrab': '#6B8E23',
+ 'orange': '#FFA500',
+ 'orangered': '#FF4500',
+ 'orchid': '#DA70D6',
+ 'palegoldenrod': '#EEE8AA',
+ 'palegreen': '#98FB98',
+ 'paleturquoise': '#AFEEEE',
+ 'palevioletred': '#DB7093',
+ 'papayawhip': '#FFEFD5',
+ 'peachpuff': '#FFDAB9',
+ 'peru': '#CD853F',
+ 'pink': '#FFC0CB',
+ 'plum': '#DDA0DD',
+ 'powderblue': '#B0E0E6',
+ 'purple': '#800080',
+ 'rebeccapurple': '#663399',
+ 'red': '#FF0000',
+ 'rosybrown': '#BC8F8F',
+ 'royalblue': '#4169E1',
+ 'saddlebrown': '#8B4513',
+ 'salmon': '#FA8072',
+ 'sandybrown': '#F4A460',
+ 'seagreen': '#2E8B57',
+ 'seashell': '#FFF5EE',
+ 'sienna': '#A0522D',
+ 'silver': '#C0C0C0',
+ 'skyblue': '#87CEEB',
+ 'slateblue': '#6A5ACD',
+ 'slategray': '#708090',
+ 'slategrey': '#708090',
+ 'snow': '#FFFAFA',
+ 'springgreen': '#00FF7F',
+ 'steelblue': '#4682B4',
+ 'tan': '#D2B48C',
+ 'teal': '#008080',
+ 'thistle': '#D8BFD8',
+ 'tomato': '#FF6347',
+ 'turquoise': '#40E0D0',
+ 'violet': '#EE82EE',
+ 'wheat': '#F5DEB3',
+ 'white': '#FFFFFF',
+ 'whitesmoke': '#F5F5F5',
+ 'yellow': '#FFFF00',
+ 'yellowgreen': '#9ACD32'}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_color_data.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_color_data.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..feb3de9c3043d55910e2649804352ae96ccbd1ec
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/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/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_constrained_layout.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_constrained_layout.py
new file mode 100644
index 0000000000000000000000000000000000000000..f5f23581bd9dc519a33753dbe171e00ee29c28d4
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_constrained_layout.py
@@ -0,0 +1,805 @@
+"""
+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.
+ """
+
+ axsdone = []
+ for sfig in fig.subfigs:
+ axsdone += 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() and
+ a not in axsdone)]
+
+ 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)
+
+ return axs
+
+
+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/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_docstring.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_docstring.py
new file mode 100644
index 0000000000000000000000000000000000000000..8cc7d623efe5c3bb3421e78bccf63b75ee76614d
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/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/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_docstring.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_docstring.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..fb52d084612399f399e6bcd3f07bca85bb010ba0
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/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/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_enums.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_enums.py
new file mode 100644
index 0000000000000000000000000000000000000000..75a09b7b5d8c7f9097e965d76fbae7bab2b41a01
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/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/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_enums.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_enums.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..714e6cfe03faab19b2a3f939a6be4ac95415e061
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_enums.pyi
@@ -0,0 +1,19 @@
+from typing import cast
+from enum import Enum
+
+
+class JoinStyle(str, Enum):
+ miter = "miter"
+ round = "round"
+ bevel = "bevel"
+ @staticmethod
+ def demo() -> None: ...
+
+
+class CapStyle(str, Enum):
+ butt = "butt"
+ projecting = "projecting"
+ round = "round"
+
+ @staticmethod
+ def demo() -> None: ...
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_fontconfig_pattern.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_fontconfig_pattern.py
new file mode 100644
index 0000000000000000000000000000000000000000..48bb2956bd7e4cb522e56d6f4d402dc4639bc0f4
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_fontconfig_pattern.py
@@ -0,0 +1,111 @@
+"""
+A module for parsing and generating `fontconfig patterns`_.
+
+.. _fontconfig patterns:
+ https://www.freedesktop.org/software/fontconfig/fontconfig-user.html
+"""
+
+# This class logically belongs in `matplotlib.font_manager`, but placing it
+# there would have created cyclical dependency problems, because it also needs
+# to be available from `matplotlib.rcsetup` (for parsing matplotlibrc files).
+
+from functools import lru_cache, partial
+import re
+
+from pyparsing import (
+ Group, Optional, ParseException, Regex, StringEnd, Suppress, ZeroOrMore, one_of)
+
+
+_family_punc = r'\\\-:,'
+_family_unescape = partial(re.compile(r'\\(?=[%s])' % _family_punc).sub, '')
+_family_escape = partial(re.compile(r'(?=[%s])' % _family_punc).sub, r'\\')
+_value_punc = r'\\=_:,'
+_value_unescape = partial(re.compile(r'\\(?=[%s])' % _value_punc).sub, '')
+_value_escape = partial(re.compile(r'(?=[%s])' % _value_punc).sub, r'\\')
+
+
+_CONSTANTS = {
+ 'thin': ('weight', 'light'),
+ 'extralight': ('weight', 'light'),
+ 'ultralight': ('weight', 'light'),
+ 'light': ('weight', 'light'),
+ 'book': ('weight', 'book'),
+ 'regular': ('weight', 'regular'),
+ 'normal': ('weight', 'normal'),
+ 'medium': ('weight', 'medium'),
+ 'demibold': ('weight', 'demibold'),
+ 'semibold': ('weight', 'semibold'),
+ 'bold': ('weight', 'bold'),
+ 'extrabold': ('weight', 'extra bold'),
+ 'black': ('weight', 'black'),
+ 'heavy': ('weight', 'heavy'),
+ 'roman': ('slant', 'normal'),
+ 'italic': ('slant', 'italic'),
+ 'oblique': ('slant', 'oblique'),
+ 'ultracondensed': ('width', 'ultra-condensed'),
+ 'extracondensed': ('width', 'extra-condensed'),
+ 'condensed': ('width', 'condensed'),
+ 'semicondensed': ('width', 'semi-condensed'),
+ 'expanded': ('width', 'expanded'),
+ 'extraexpanded': ('width', 'extra-expanded'),
+ 'ultraexpanded': ('width', 'ultra-expanded'),
+}
+
+
+@lru_cache # The parser instance is a singleton.
+def _make_fontconfig_parser():
+ def comma_separated(elem):
+ return elem + ZeroOrMore(Suppress(",") + elem)
+
+ family = Regex(fr"([^{_family_punc}]|(\\[{_family_punc}]))*")
+ size = Regex(r"([0-9]+\.?[0-9]*|\.[0-9]+)")
+ name = Regex(r"[a-z]+")
+ value = Regex(fr"([^{_value_punc}]|(\\[{_value_punc}]))*")
+ prop = Group((name + Suppress("=") + comma_separated(value)) | one_of(_CONSTANTS))
+ return (
+ Optional(comma_separated(family)("families"))
+ + Optional("-" + comma_separated(size)("sizes"))
+ + ZeroOrMore(":" + prop("properties*"))
+ + StringEnd()
+ )
+
+
+# `parse_fontconfig_pattern` is a bottleneck during the tests because it is
+# repeatedly called when the rcParams are reset (to validate the default
+# fonts). In practice, the cache size doesn't grow beyond a few dozen entries
+# during the test suite.
+@lru_cache
+def parse_fontconfig_pattern(pattern):
+ """
+ Parse a fontconfig *pattern* into a dict that can initialize a
+ `.font_manager.FontProperties` object.
+ """
+ parser = _make_fontconfig_parser()
+ try:
+ parse = parser.parse_string(pattern)
+ except ParseException as err:
+ # explain becomes a plain method on pyparsing 3 (err.explain(0)).
+ raise ValueError("\n" + ParseException.explain(err, 0)) from None
+ parser.reset_cache()
+ props = {}
+ if "families" in parse:
+ props["family"] = [*map(_family_unescape, parse["families"])]
+ if "sizes" in parse:
+ props["size"] = [*parse["sizes"]]
+ for prop in parse.get("properties", []):
+ if len(prop) == 1:
+ prop = _CONSTANTS[prop[0]]
+ k, *v = prop
+ props.setdefault(k, []).extend(map(_value_unescape, v))
+ return props
+
+
+def generate_fontconfig_pattern(d):
+ """Convert a `.FontProperties` to a fontconfig pattern string."""
+ kvs = [(k, getattr(d, f"get_{k}")())
+ for k in ["style", "variant", "weight", "stretch", "file", "size"]]
+ # Families is given first without a leading keyword. Other entries (which
+ # are necessarily scalar) are given as key=value, skipping Nones.
+ return (",".join(_family_escape(f) for f in d.get_family())
+ + "".join(f":{k}={_value_escape(str(v))}"
+ for k, v in kvs if v is not None))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_image.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_image.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_internal_utils.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_internal_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..0223aa593bb2cb20b58f2b9e41bdc0dfa5ceed35
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_internal_utils.py
@@ -0,0 +1,64 @@
+"""
+Internal debugging utilities, that are not expected to be used in the rest of
+the codebase.
+
+WARNING: Code in this module may change without prior notice!
+"""
+
+from io import StringIO
+from pathlib import Path
+import subprocess
+
+from matplotlib.transforms import TransformNode
+
+
+def graphviz_dump_transform(transform, dest, *, highlight=None):
+ """
+ Generate a graphical representation of the transform tree for *transform*
+ using the :program:`dot` program (which this function depends on). The
+ output format (png, dot, etc.) is determined from the suffix of *dest*.
+
+ Parameters
+ ----------
+ transform : `~matplotlib.transform.Transform`
+ The represented transform.
+ dest : str
+ Output filename. The extension must be one of the formats supported
+ by :program:`dot`, e.g. png, svg, dot, ...
+ (see https://www.graphviz.org/doc/info/output.html).
+ highlight : list of `~matplotlib.transform.Transform` or None
+ The transforms in the tree to be drawn in bold.
+ If *None*, *transform* is highlighted.
+ """
+
+ if highlight is None:
+ highlight = [transform]
+ seen = set()
+
+ def recurse(root, buf):
+ if id(root) in seen:
+ return
+ seen.add(id(root))
+ props = {}
+ label = type(root).__name__
+ if root._invalid:
+ label = f'[{label}]'
+ if root in highlight:
+ props['style'] = 'bold'
+ props['shape'] = 'box'
+ props['label'] = '"%s"' % label
+ props = ' '.join(map('{0[0]}={0[1]}'.format, props.items()))
+ buf.write(f'{id(root)} [{props}];\n')
+ for key, val in vars(root).items():
+ if isinstance(val, TransformNode) and id(root) in val._parents:
+ buf.write(f'"{id(root)}" -> "{id(val)}" '
+ f'[label="{key}", fontsize=10];\n')
+ recurse(val, buf)
+
+ buf = StringIO()
+ buf.write('digraph G {\n')
+ recurse(transform, buf)
+ buf.write('}\n')
+ subprocess.run(
+ ['dot', '-T', Path(dest).suffix[1:], '-o', dest],
+ input=buf.getvalue().encode('utf-8'), check=True)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_layoutgrid.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_layoutgrid.py
new file mode 100644
index 0000000000000000000000000000000000000000..8f81b14765b68fa1f7480c3d34ba74245e39b84f
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_layoutgrid.py
@@ -0,0 +1,547 @@
+"""
+A layoutgrid is a nrows by ncols set of boxes, meant to be used by
+`._constrained_layout`, each box is analogous to a subplotspec element of
+a gridspec.
+
+Each box is defined by left[ncols], right[ncols], bottom[nrows] and top[nrows],
+and by two editable margins for each side. The main margin gets its value
+set by the size of ticklabels, titles, etc on each Axes that is in the figure.
+The outer margin is the padding around the Axes, and space for any
+colorbars.
+
+The "inner" widths and heights of these boxes are then constrained to be the
+same (relative the values of `width_ratios[ncols]` and `height_ratios[nrows]`).
+
+The layoutgrid is then constrained to be contained within a parent layoutgrid,
+its column(s) and row(s) specified when it is created.
+"""
+
+import itertools
+import kiwisolver as kiwi
+import logging
+import numpy as np
+
+import matplotlib as mpl
+import matplotlib.patches as mpatches
+from matplotlib.transforms import Bbox
+
+_log = logging.getLogger(__name__)
+
+
+class LayoutGrid:
+ """
+ Analogous to a gridspec, and contained in another LayoutGrid.
+ """
+
+ def __init__(self, parent=None, parent_pos=(0, 0),
+ parent_inner=False, name='', ncols=1, nrows=1,
+ h_pad=None, w_pad=None, width_ratios=None,
+ height_ratios=None):
+ Variable = kiwi.Variable
+ self.parent_pos = parent_pos
+ self.parent_inner = parent_inner
+ self.name = name + seq_id()
+ if isinstance(parent, LayoutGrid):
+ self.name = f'{parent.name}.{self.name}'
+ self.nrows = nrows
+ self.ncols = ncols
+ self.height_ratios = np.atleast_1d(height_ratios)
+ if height_ratios is None:
+ self.height_ratios = np.ones(nrows)
+ self.width_ratios = np.atleast_1d(width_ratios)
+ if width_ratios is None:
+ self.width_ratios = np.ones(ncols)
+
+ sn = self.name + '_'
+ if not isinstance(parent, LayoutGrid):
+ # parent can be a rect if not a LayoutGrid
+ # allows specifying a rectangle to contain the layout.
+ self.solver = kiwi.Solver()
+ else:
+ parent.add_child(self, *parent_pos)
+ self.solver = parent.solver
+ # keep track of artist associated w/ this layout. Can be none
+ self.artists = np.empty((nrows, ncols), dtype=object)
+ self.children = np.empty((nrows, ncols), dtype=object)
+
+ self.margins = {}
+ self.margin_vals = {}
+ # all the boxes in each column share the same left/right margins:
+ for todo in ['left', 'right', 'leftcb', 'rightcb']:
+ # track the value so we can change only if a margin is larger
+ # than the current value
+ self.margin_vals[todo] = np.zeros(ncols)
+
+ sol = self.solver
+
+ self.lefts = [Variable(f'{sn}lefts[{i}]') for i in range(ncols)]
+ self.rights = [Variable(f'{sn}rights[{i}]') for i in range(ncols)]
+ for todo in ['left', 'right', 'leftcb', 'rightcb']:
+ self.margins[todo] = [Variable(f'{sn}margins[{todo}][{i}]')
+ for i in range(ncols)]
+ for i in range(ncols):
+ sol.addEditVariable(self.margins[todo][i], 'strong')
+
+ for todo in ['bottom', 'top', 'bottomcb', 'topcb']:
+ self.margins[todo] = np.empty((nrows), dtype=object)
+ self.margin_vals[todo] = np.zeros(nrows)
+
+ self.bottoms = [Variable(f'{sn}bottoms[{i}]') for i in range(nrows)]
+ self.tops = [Variable(f'{sn}tops[{i}]') for i in range(nrows)]
+ for todo in ['bottom', 'top', 'bottomcb', 'topcb']:
+ self.margins[todo] = [Variable(f'{sn}margins[{todo}][{i}]')
+ for i in range(nrows)]
+ for i in range(nrows):
+ sol.addEditVariable(self.margins[todo][i], 'strong')
+
+ # set these margins to zero by default. They will be edited as
+ # children are filled.
+ self.reset_margins()
+ self.add_constraints(parent)
+
+ self.h_pad = h_pad
+ self.w_pad = w_pad
+
+ def __repr__(self):
+ str = f'LayoutBox: {self.name:25s} {self.nrows}x{self.ncols},\n'
+ for i in range(self.nrows):
+ for j in range(self.ncols):
+ str += f'{i}, {j}: '\
+ f'L{self.lefts[j].value():1.3f}, ' \
+ f'B{self.bottoms[i].value():1.3f}, ' \
+ f'R{self.rights[j].value():1.3f}, ' \
+ f'T{self.tops[i].value():1.3f}, ' \
+ f'ML{self.margins["left"][j].value():1.3f}, ' \
+ f'MR{self.margins["right"][j].value():1.3f}, ' \
+ f'MB{self.margins["bottom"][i].value():1.3f}, ' \
+ f'MT{self.margins["top"][i].value():1.3f}, \n'
+ return str
+
+ def reset_margins(self):
+ """
+ Reset all the margins to zero. Must do this after changing
+ figure size, for instance, because the relative size of the
+ axes labels etc changes.
+ """
+ for todo in ['left', 'right', 'bottom', 'top',
+ 'leftcb', 'rightcb', 'bottomcb', 'topcb']:
+ self.edit_margins(todo, 0.0)
+
+ def add_constraints(self, parent):
+ # define self-consistent constraints
+ self.hard_constraints()
+ # define relationship with parent layoutgrid:
+ self.parent_constraints(parent)
+ # define relative widths of the grid cells to each other
+ # and stack horizontally and vertically.
+ self.grid_constraints()
+
+ def hard_constraints(self):
+ """
+ These are the redundant constraints, plus ones that make the
+ rest of the code easier.
+ """
+ for i in range(self.ncols):
+ hc = [self.rights[i] >= self.lefts[i],
+ (self.rights[i] - self.margins['right'][i] -
+ self.margins['rightcb'][i] >=
+ self.lefts[i] - self.margins['left'][i] -
+ self.margins['leftcb'][i])
+ ]
+ for c in hc:
+ self.solver.addConstraint(c | 'required')
+
+ for i in range(self.nrows):
+ hc = [self.tops[i] >= self.bottoms[i],
+ (self.tops[i] - self.margins['top'][i] -
+ self.margins['topcb'][i] >=
+ self.bottoms[i] - self.margins['bottom'][i] -
+ self.margins['bottomcb'][i])
+ ]
+ for c in hc:
+ self.solver.addConstraint(c | 'required')
+
+ def add_child(self, child, i=0, j=0):
+ # np.ix_ returns the cross product of i and j indices
+ self.children[np.ix_(np.atleast_1d(i), np.atleast_1d(j))] = child
+
+ def parent_constraints(self, parent):
+ # constraints that are due to the parent...
+ # i.e. the first column's left is equal to the
+ # parent's left, the last column right equal to the
+ # parent's right...
+ if not isinstance(parent, LayoutGrid):
+ # specify a rectangle in figure coordinates
+ hc = [self.lefts[0] == parent[0],
+ self.rights[-1] == parent[0] + parent[2],
+ # top and bottom reversed order...
+ self.tops[0] == parent[1] + parent[3],
+ self.bottoms[-1] == parent[1]]
+ else:
+ rows, cols = self.parent_pos
+ rows = np.atleast_1d(rows)
+ cols = np.atleast_1d(cols)
+
+ left = parent.lefts[cols[0]]
+ right = parent.rights[cols[-1]]
+ top = parent.tops[rows[0]]
+ bottom = parent.bottoms[rows[-1]]
+ if self.parent_inner:
+ # the layout grid is contained inside the inner
+ # grid of the parent.
+ left += parent.margins['left'][cols[0]]
+ left += parent.margins['leftcb'][cols[0]]
+ right -= parent.margins['right'][cols[-1]]
+ right -= parent.margins['rightcb'][cols[-1]]
+ top -= parent.margins['top'][rows[0]]
+ top -= parent.margins['topcb'][rows[0]]
+ bottom += parent.margins['bottom'][rows[-1]]
+ bottom += parent.margins['bottomcb'][rows[-1]]
+ hc = [self.lefts[0] == left,
+ self.rights[-1] == right,
+ # from top to bottom
+ self.tops[0] == top,
+ self.bottoms[-1] == bottom]
+ for c in hc:
+ self.solver.addConstraint(c | 'required')
+
+ def grid_constraints(self):
+ # constrain the ratio of the inner part of the grids
+ # to be the same (relative to width_ratios)
+
+ # constrain widths:
+ w = (self.rights[0] - self.margins['right'][0] -
+ self.margins['rightcb'][0])
+ w = (w - self.lefts[0] - self.margins['left'][0] -
+ self.margins['leftcb'][0])
+ w0 = w / self.width_ratios[0]
+ # from left to right
+ for i in range(1, self.ncols):
+ w = (self.rights[i] - self.margins['right'][i] -
+ self.margins['rightcb'][i])
+ w = (w - self.lefts[i] - self.margins['left'][i] -
+ self.margins['leftcb'][i])
+ c = (w == w0 * self.width_ratios[i])
+ self.solver.addConstraint(c | 'strong')
+ # constrain the grid cells to be directly next to each other.
+ c = (self.rights[i - 1] == self.lefts[i])
+ self.solver.addConstraint(c | 'strong')
+
+ # constrain heights:
+ h = self.tops[0] - self.margins['top'][0] - self.margins['topcb'][0]
+ h = (h - self.bottoms[0] - self.margins['bottom'][0] -
+ self.margins['bottomcb'][0])
+ h0 = h / self.height_ratios[0]
+ # from top to bottom:
+ for i in range(1, self.nrows):
+ h = (self.tops[i] - self.margins['top'][i] -
+ self.margins['topcb'][i])
+ h = (h - self.bottoms[i] - self.margins['bottom'][i] -
+ self.margins['bottomcb'][i])
+ c = (h == h0 * self.height_ratios[i])
+ self.solver.addConstraint(c | 'strong')
+ # constrain the grid cells to be directly above each other.
+ c = (self.bottoms[i - 1] == self.tops[i])
+ self.solver.addConstraint(c | 'strong')
+
+ # Margin editing: The margins are variable and meant to
+ # contain things of a fixed size like axes labels, tick labels, titles
+ # etc
+ def edit_margin(self, todo, size, cell):
+ """
+ Change the size of the margin for one cell.
+
+ Parameters
+ ----------
+ todo : string (one of 'left', 'right', 'bottom', 'top')
+ margin to alter.
+
+ size : float
+ Size of the margin. If it is larger than the existing minimum it
+ updates the margin size. Fraction of figure size.
+
+ cell : int
+ Cell column or row to edit.
+ """
+ self.solver.suggestValue(self.margins[todo][cell], size)
+ self.margin_vals[todo][cell] = size
+
+ def edit_margin_min(self, todo, size, cell=0):
+ """
+ Change the minimum size of the margin for one cell.
+
+ Parameters
+ ----------
+ todo : string (one of 'left', 'right', 'bottom', 'top')
+ margin to alter.
+
+ size : float
+ Minimum size of the margin . If it is larger than the
+ existing minimum it updates the margin size. Fraction of
+ figure size.
+
+ cell : int
+ Cell column or row to edit.
+ """
+
+ if size > self.margin_vals[todo][cell]:
+ self.edit_margin(todo, size, cell)
+
+ def edit_margins(self, todo, size):
+ """
+ Change the size of all the margin of all the cells in the layout grid.
+
+ Parameters
+ ----------
+ todo : string (one of 'left', 'right', 'bottom', 'top')
+ margin to alter.
+
+ size : float
+ Size to set the margins. Fraction of figure size.
+ """
+
+ for i in range(len(self.margin_vals[todo])):
+ self.edit_margin(todo, size, i)
+
+ def edit_all_margins_min(self, todo, size):
+ """
+ Change the minimum size of all the margin of all
+ the cells in the layout grid.
+
+ Parameters
+ ----------
+ todo : {'left', 'right', 'bottom', 'top'}
+ The margin to alter.
+
+ size : float
+ Minimum size of the margin. If it is larger than the
+ existing minimum it updates the margin size. Fraction of
+ figure size.
+ """
+
+ for i in range(len(self.margin_vals[todo])):
+ self.edit_margin_min(todo, size, i)
+
+ def edit_outer_margin_mins(self, margin, ss):
+ """
+ Edit all four margin minimums in one statement.
+
+ Parameters
+ ----------
+ margin : dict
+ size of margins in a dict with keys 'left', 'right', 'bottom',
+ 'top'
+
+ ss : SubplotSpec
+ defines the subplotspec these margins should be applied to
+ """
+
+ self.edit_margin_min('left', margin['left'], ss.colspan.start)
+ self.edit_margin_min('leftcb', margin['leftcb'], ss.colspan.start)
+ self.edit_margin_min('right', margin['right'], ss.colspan.stop - 1)
+ self.edit_margin_min('rightcb', margin['rightcb'], ss.colspan.stop - 1)
+ # rows are from the top down:
+ self.edit_margin_min('top', margin['top'], ss.rowspan.start)
+ self.edit_margin_min('topcb', margin['topcb'], ss.rowspan.start)
+ self.edit_margin_min('bottom', margin['bottom'], ss.rowspan.stop - 1)
+ self.edit_margin_min('bottomcb', margin['bottomcb'],
+ ss.rowspan.stop - 1)
+
+ def get_margins(self, todo, col):
+ """Return the margin at this position"""
+ return self.margin_vals[todo][col]
+
+ def get_outer_bbox(self, rows=0, cols=0):
+ """
+ Return the outer bounding box of the subplot specs
+ given by rows and cols. rows and cols can be spans.
+ """
+ rows = np.atleast_1d(rows)
+ cols = np.atleast_1d(cols)
+
+ bbox = Bbox.from_extents(
+ self.lefts[cols[0]].value(),
+ self.bottoms[rows[-1]].value(),
+ self.rights[cols[-1]].value(),
+ self.tops[rows[0]].value())
+ return bbox
+
+ def get_inner_bbox(self, rows=0, cols=0):
+ """
+ Return the inner bounding box of the subplot specs
+ given by rows and cols. rows and cols can be spans.
+ """
+ rows = np.atleast_1d(rows)
+ cols = np.atleast_1d(cols)
+
+ bbox = Bbox.from_extents(
+ (self.lefts[cols[0]].value() +
+ self.margins['left'][cols[0]].value() +
+ self.margins['leftcb'][cols[0]].value()),
+ (self.bottoms[rows[-1]].value() +
+ self.margins['bottom'][rows[-1]].value() +
+ self.margins['bottomcb'][rows[-1]].value()),
+ (self.rights[cols[-1]].value() -
+ self.margins['right'][cols[-1]].value() -
+ self.margins['rightcb'][cols[-1]].value()),
+ (self.tops[rows[0]].value() -
+ self.margins['top'][rows[0]].value() -
+ self.margins['topcb'][rows[0]].value())
+ )
+ return bbox
+
+ def get_bbox_for_cb(self, rows=0, cols=0):
+ """
+ Return the bounding box that includes the
+ decorations but, *not* the colorbar...
+ """
+ rows = np.atleast_1d(rows)
+ cols = np.atleast_1d(cols)
+
+ bbox = Bbox.from_extents(
+ (self.lefts[cols[0]].value() +
+ self.margins['leftcb'][cols[0]].value()),
+ (self.bottoms[rows[-1]].value() +
+ self.margins['bottomcb'][rows[-1]].value()),
+ (self.rights[cols[-1]].value() -
+ self.margins['rightcb'][cols[-1]].value()),
+ (self.tops[rows[0]].value() -
+ self.margins['topcb'][rows[0]].value())
+ )
+ return bbox
+
+ def get_left_margin_bbox(self, rows=0, cols=0):
+ """
+ Return the left margin bounding box of the subplot specs
+ given by rows and cols. rows and cols can be spans.
+ """
+ rows = np.atleast_1d(rows)
+ cols = np.atleast_1d(cols)
+
+ bbox = Bbox.from_extents(
+ (self.lefts[cols[0]].value() +
+ self.margins['leftcb'][cols[0]].value()),
+ (self.bottoms[rows[-1]].value()),
+ (self.lefts[cols[0]].value() +
+ self.margins['leftcb'][cols[0]].value() +
+ self.margins['left'][cols[0]].value()),
+ (self.tops[rows[0]].value()))
+ return bbox
+
+ def get_bottom_margin_bbox(self, rows=0, cols=0):
+ """
+ Return the left margin bounding box of the subplot specs
+ given by rows and cols. rows and cols can be spans.
+ """
+ rows = np.atleast_1d(rows)
+ cols = np.atleast_1d(cols)
+
+ bbox = Bbox.from_extents(
+ (self.lefts[cols[0]].value()),
+ (self.bottoms[rows[-1]].value() +
+ self.margins['bottomcb'][rows[-1]].value()),
+ (self.rights[cols[-1]].value()),
+ (self.bottoms[rows[-1]].value() +
+ self.margins['bottom'][rows[-1]].value() +
+ self.margins['bottomcb'][rows[-1]].value()
+ ))
+ return bbox
+
+ def get_right_margin_bbox(self, rows=0, cols=0):
+ """
+ Return the left margin bounding box of the subplot specs
+ given by rows and cols. rows and cols can be spans.
+ """
+ rows = np.atleast_1d(rows)
+ cols = np.atleast_1d(cols)
+
+ bbox = Bbox.from_extents(
+ (self.rights[cols[-1]].value() -
+ self.margins['right'][cols[-1]].value() -
+ self.margins['rightcb'][cols[-1]].value()),
+ (self.bottoms[rows[-1]].value()),
+ (self.rights[cols[-1]].value() -
+ self.margins['rightcb'][cols[-1]].value()),
+ (self.tops[rows[0]].value()))
+ return bbox
+
+ def get_top_margin_bbox(self, rows=0, cols=0):
+ """
+ Return the left margin bounding box of the subplot specs
+ given by rows and cols. rows and cols can be spans.
+ """
+ rows = np.atleast_1d(rows)
+ cols = np.atleast_1d(cols)
+
+ bbox = Bbox.from_extents(
+ (self.lefts[cols[0]].value()),
+ (self.tops[rows[0]].value() -
+ self.margins['topcb'][rows[0]].value()),
+ (self.rights[cols[-1]].value()),
+ (self.tops[rows[0]].value() -
+ self.margins['topcb'][rows[0]].value() -
+ self.margins['top'][rows[0]].value()))
+ return bbox
+
+ def update_variables(self):
+ """
+ Update the variables for the solver attached to this layoutgrid.
+ """
+ self.solver.updateVariables()
+
+_layoutboxobjnum = itertools.count()
+
+
+def seq_id():
+ """Generate a short sequential id for layoutbox objects."""
+ return '%06d' % next(_layoutboxobjnum)
+
+
+def plot_children(fig, lg=None, level=0):
+ """Simple plotting to show where boxes are."""
+ if lg is None:
+ _layoutgrids = fig.get_layout_engine().execute(fig)
+ lg = _layoutgrids[fig]
+ colors = mpl.rcParams["axes.prop_cycle"].by_key()["color"]
+ col = colors[level]
+ for i in range(lg.nrows):
+ for j in range(lg.ncols):
+ bb = lg.get_outer_bbox(rows=i, cols=j)
+ fig.add_artist(
+ mpatches.Rectangle(bb.p0, bb.width, bb.height, linewidth=1,
+ edgecolor='0.7', facecolor='0.7',
+ alpha=0.2, transform=fig.transFigure,
+ zorder=-3))
+ bbi = lg.get_inner_bbox(rows=i, cols=j)
+ fig.add_artist(
+ mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=2,
+ edgecolor=col, facecolor='none',
+ transform=fig.transFigure, zorder=-2))
+
+ bbi = lg.get_left_margin_bbox(rows=i, cols=j)
+ fig.add_artist(
+ mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=0,
+ edgecolor='none', alpha=0.2,
+ facecolor=[0.5, 0.7, 0.5],
+ transform=fig.transFigure, zorder=-2))
+ bbi = lg.get_right_margin_bbox(rows=i, cols=j)
+ fig.add_artist(
+ mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=0,
+ edgecolor='none', alpha=0.2,
+ facecolor=[0.7, 0.5, 0.5],
+ transform=fig.transFigure, zorder=-2))
+ bbi = lg.get_bottom_margin_bbox(rows=i, cols=j)
+ fig.add_artist(
+ mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=0,
+ edgecolor='none', alpha=0.2,
+ facecolor=[0.5, 0.5, 0.7],
+ transform=fig.transFigure, zorder=-2))
+ bbi = lg.get_top_margin_bbox(rows=i, cols=j)
+ fig.add_artist(
+ mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=0,
+ edgecolor='none', alpha=0.2,
+ facecolor=[0.7, 0.2, 0.7],
+ transform=fig.transFigure, zorder=-2))
+ for ch in lg.children.flat:
+ if ch is not None:
+ plot_children(fig, ch, level=level+1)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_mathtext.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_mathtext.py
new file mode 100644
index 0000000000000000000000000000000000000000..cf35dc1de7db2b8b7ea84c9cc5c2ba9ad6b6c5a0
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_mathtext.py
@@ -0,0 +1,2855 @@
+"""
+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, Group, NotAny, OneOrMore, Optional,
+ ParseBaseException, ParseException, ParseExpression, ParseFatalException,
+ ParserElement, ParseResults, QuotedString, Regex, StringEnd, ZeroOrMore,
+ pyparsing_common, nested_expr, one_of)
+
+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
+
+
+if T.TYPE_CHECKING:
+ from collections.abc import Iterable
+ from .ft2font import Glyph
+
+ParserElement.enable_packrat()
+_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'\rightparen', ')'),
+ (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().set_parse_action(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.set_name(key)
+ # Set actions
+ if hasattr(self, key):
+ val.set_parse_action(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 = one_of(self._space_widths)("space")
+
+ p.style_literal = one_of(
+ [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").leave_whitespace()
+ p.unknown_symbol = Regex(r"\\[A-Za-z]+")("name")
+
+ p.font = csnames("font", self._fontnames)
+ p.start_group = Optional(r"\math" + one_of(self._fontnames)("font")) + "{"
+ p.end_group = Literal("}")
+
+ p.delim = one_of(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('{', '\\', end_quote_char="}"))
+
+ 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(one_of(["_", "^"]) - 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('$', '\\', unquote_results=False)
+ p.non_math = Regex(r"(?:(?:\\[$])|[^$])*").leave_whitespace()
+ 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.parse_string(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.reset_cache()
+ 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.as_list())]
+
+ def math_string(self, toks: ParseResults) -> ParseResults:
+ return self._math_expression.parse_string(toks[0][1:-1], parse_all=True)
+
+ def math(self, toks: ParseResults) -> T.Any:
+ hlist = Hlist(toks.as_list())
+ 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.convert_to_float)
+
+ 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
+ isinstance(new_children[-2], Char)):
+ new_children = new_children[:-1]
+ last_char = new_children[-1]
+ if isinstance(last_char, Char):
+ 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: list[Node] = [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"].as_list() 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/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_mathtext_data.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_mathtext_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..5819ee7430447f9ef5f6e760b65cdd5933ef9395
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/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/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_path.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_path.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..456905528b28e0f4eea31ec9d86433fb43767b85
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/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/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_pylab_helpers.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_pylab_helpers.py
new file mode 100644
index 0000000000000000000000000000000000000000..a3861aef592008a84ffddadb7a0c76c8833a30af
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_pylab_helpers.py
@@ -0,0 +1,134 @@
+"""
+Manage figures for the pyplot interface.
+"""
+
+import atexit
+from collections import OrderedDict
+
+
+class Gcf:
+ """
+ Singleton to maintain the relation between figures and their managers, and
+ keep track of and "active" figure and manager.
+
+ The canvas of a figure created through pyplot is associated with a figure
+ manager, which handles the interaction between the figure and the backend.
+ pyplot keeps track of figure managers using an identifier, the "figure
+ number" or "manager number" (which can actually be any hashable value);
+ this number is available as the :attr:`number` attribute of the manager.
+
+ This class is never instantiated; it consists of an `OrderedDict` mapping
+ figure/manager numbers to managers, and a set of class methods that
+ manipulate this `OrderedDict`.
+
+ Attributes
+ ----------
+ figs : OrderedDict
+ `OrderedDict` mapping numbers to managers; the active manager is at the
+ end.
+ """
+
+ figs = OrderedDict()
+
+ @classmethod
+ def get_fig_manager(cls, num):
+ """
+ If manager number *num* exists, make it the active one and return it;
+ otherwise return *None*.
+ """
+ manager = cls.figs.get(num, None)
+ if manager is not None:
+ cls.set_active(manager)
+ return manager
+
+ @classmethod
+ def destroy(cls, num):
+ """
+ Destroy manager *num* -- either a manager instance or a manager number.
+
+ In the interactive backends, this is bound to the window "destroy" and
+ "delete" events.
+
+ It is recommended to pass a manager instance, to avoid confusion when
+ two managers share the same number.
+ """
+ if all(hasattr(num, attr) for attr in ["num", "destroy"]):
+ manager = num
+ if cls.figs.get(manager.num) is manager:
+ cls.figs.pop(manager.num)
+ else:
+ try:
+ manager = cls.figs.pop(num)
+ except KeyError:
+ return
+ if hasattr(manager, "_cidgcf"):
+ manager.canvas.mpl_disconnect(manager._cidgcf)
+ manager.destroy()
+
+ @classmethod
+ def destroy_fig(cls, fig):
+ """Destroy figure *fig*."""
+ num = next((manager.num for manager in cls.figs.values()
+ if manager.canvas.figure == fig), None)
+ if num is not None:
+ cls.destroy(num)
+
+ @classmethod
+ def destroy_all(cls):
+ """Destroy all figures."""
+ for manager in list(cls.figs.values()):
+ manager.canvas.mpl_disconnect(manager._cidgcf)
+ manager.destroy()
+ cls.figs.clear()
+
+ @classmethod
+ def has_fignum(cls, num):
+ """Return whether figure number *num* exists."""
+ return num in cls.figs
+
+ @classmethod
+ def get_all_fig_managers(cls):
+ """Return a list of figure managers."""
+ return list(cls.figs.values())
+
+ @classmethod
+ def get_num_fig_managers(cls):
+ """Return the number of figures being managed."""
+ return len(cls.figs)
+
+ @classmethod
+ def get_active(cls):
+ """Return the active manager, or *None* if there is no manager."""
+ return next(reversed(cls.figs.values())) if cls.figs else None
+
+ @classmethod
+ def _set_new_active_manager(cls, manager):
+ """Adopt *manager* into pyplot and make it the active manager."""
+ if not hasattr(manager, "_cidgcf"):
+ manager._cidgcf = manager.canvas.mpl_connect(
+ "button_press_event", lambda event: cls.set_active(manager))
+ fig = manager.canvas.figure
+ fig._number = manager.num
+ label = fig.get_label()
+ if label:
+ manager.set_window_title(label)
+ cls.set_active(manager)
+
+ @classmethod
+ def set_active(cls, manager):
+ """Make *manager* the active manager."""
+ cls.figs[manager.num] = manager
+ cls.figs.move_to_end(manager.num)
+
+ @classmethod
+ def draw_all(cls, force=False):
+ """
+ Redraw all stale managed figures, or, if *force* is True, all managed
+ figures.
+ """
+ for manager in cls.get_all_fig_managers():
+ if force or manager.canvas.figure.stale:
+ manager.canvas.draw_idle()
+
+
+atexit.register(Gcf.destroy_all)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_pylab_helpers.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_pylab_helpers.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..bdd8cfba3173030b37b24af412970cbb62fee3ef
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/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/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_qhull.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_qhull.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_text_helpers.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_text_helpers.py
new file mode 100644
index 0000000000000000000000000000000000000000..b9603b114bc245ecf32da926573ddb4157210c7a
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_text_helpers.py
@@ -0,0 +1,82 @@
+"""
+Low-level text helper utilities.
+"""
+
+from __future__ import annotations
+
+import dataclasses
+
+from . import _api
+from .ft2font import FT2Font, Kerning, LoadFlags
+
+
+@dataclasses.dataclass(frozen=True)
+class LayoutItem:
+ ft_object: FT2Font
+ char: str
+ glyph_idx: int
+ x: float
+ prev_kern: float
+
+
+def warn_on_missing_glyph(codepoint, fontnames):
+ _api.warn_external(
+ f"Glyph {codepoint} "
+ f"({chr(codepoint).encode('ascii', 'namereplace').decode('ascii')}) "
+ f"missing from font(s) {fontnames}.")
+
+ block = ("Hebrew" if 0x0590 <= codepoint <= 0x05ff else
+ "Arabic" if 0x0600 <= codepoint <= 0x06ff else
+ "Devanagari" if 0x0900 <= codepoint <= 0x097f else
+ "Bengali" if 0x0980 <= codepoint <= 0x09ff else
+ "Gurmukhi" if 0x0a00 <= codepoint <= 0x0a7f else
+ "Gujarati" if 0x0a80 <= codepoint <= 0x0aff else
+ "Oriya" if 0x0b00 <= codepoint <= 0x0b7f else
+ "Tamil" if 0x0b80 <= codepoint <= 0x0bff else
+ "Telugu" if 0x0c00 <= codepoint <= 0x0c7f else
+ "Kannada" if 0x0c80 <= codepoint <= 0x0cff else
+ "Malayalam" if 0x0d00 <= codepoint <= 0x0d7f else
+ "Sinhala" if 0x0d80 <= codepoint <= 0x0dff else
+ None)
+ if block:
+ _api.warn_external(
+ f"Matplotlib currently does not support {block} natively.")
+
+
+def layout(string, font, *, kern_mode=Kerning.DEFAULT):
+ """
+ Render *string* with *font*.
+
+ For each character in *string*, yield a LayoutItem instance. When such an instance
+ is yielded, the font's glyph is set to the corresponding character.
+
+ Parameters
+ ----------
+ string : str
+ The string to be rendered.
+ font : FT2Font
+ The font.
+ kern_mode : Kerning
+ A FreeType kerning mode.
+
+ Yields
+ ------
+ LayoutItem
+ """
+ x = 0
+ prev_glyph_idx = None
+ char_to_font = font._get_fontmap(string)
+ base_font = font
+ for char in string:
+ # This has done the fallback logic
+ font = char_to_font.get(char, base_font)
+ glyph_idx = font.get_char_index(ord(char))
+ kern = (
+ base_font.get_kerning(prev_glyph_idx, glyph_idx, kern_mode) / 64
+ if prev_glyph_idx is not None else 0.
+ )
+ x += kern
+ glyph = font.load_glyph(glyph_idx, flags=LoadFlags.NO_HINTING)
+ yield LayoutItem(font, char, glyph_idx, x, kern)
+ x += glyph.linearHoriAdvance / 65536
+ prev_glyph_idx = glyph_idx
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_tight_bbox.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_tight_bbox.py
new file mode 100644
index 0000000000000000000000000000000000000000..db72bbdff020680dfd833229cac41e9b33e428ee
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_tight_bbox.py
@@ -0,0 +1,84 @@
+"""
+Helper module for the *bbox_inches* parameter in `.Figure.savefig`.
+"""
+
+from matplotlib.transforms import Bbox, TransformedBbox, Affine2D
+
+
+def adjust_bbox(fig, bbox_inches, fixed_dpi=None):
+ """
+ Temporarily adjust the figure so that only the specified area
+ (bbox_inches) is saved.
+
+ It modifies fig.bbox, fig.bbox_inches,
+ fig.transFigure._boxout, and fig.patch. While the figure size
+ changes, the scale of the original figure is conserved. A
+ function which restores the original values are returned.
+ """
+ origBbox = fig.bbox
+ origBboxInches = fig.bbox_inches
+ _boxout = fig.transFigure._boxout
+
+ old_aspect = []
+ locator_list = []
+ sentinel = object()
+ for ax in fig.axes:
+ locator = ax.get_axes_locator()
+ if locator is not None:
+ ax.apply_aspect(locator(ax, None))
+ locator_list.append(locator)
+ current_pos = ax.get_position(original=False).frozen()
+ ax.set_axes_locator(lambda a, r, _pos=current_pos: _pos)
+ # override the method that enforces the aspect ratio on the Axes
+ if 'apply_aspect' in ax.__dict__:
+ old_aspect.append(ax.apply_aspect)
+ else:
+ old_aspect.append(sentinel)
+ ax.apply_aspect = lambda pos=None: None
+
+ def restore_bbox():
+ for ax, loc, aspect in zip(fig.axes, locator_list, old_aspect):
+ ax.set_axes_locator(loc)
+ if aspect is sentinel:
+ # delete our no-op function which un-hides the original method
+ del ax.apply_aspect
+ else:
+ ax.apply_aspect = aspect
+
+ fig.bbox = origBbox
+ fig.bbox_inches = origBboxInches
+ fig.transFigure._boxout = _boxout
+ fig.transFigure.invalidate()
+ fig.patch.set_bounds(0, 0, 1, 1)
+
+ if fixed_dpi is None:
+ fixed_dpi = fig.dpi
+ tr = Affine2D().scale(fixed_dpi)
+ dpi_scale = fixed_dpi / fig.dpi
+
+ fig.bbox_inches = Bbox.from_bounds(0, 0, *bbox_inches.size)
+ x0, y0 = tr.transform(bbox_inches.p0)
+ w1, h1 = fig.bbox.size * dpi_scale
+ fig.transFigure._boxout = Bbox.from_bounds(-x0, -y0, w1, h1)
+ fig.transFigure.invalidate()
+
+ fig.bbox = TransformedBbox(fig.bbox_inches, tr)
+
+ fig.patch.set_bounds(x0 / w1, y0 / h1,
+ fig.bbox.width / w1, fig.bbox.height / h1)
+
+ return restore_bbox
+
+
+def process_figure_for_rasterizing(fig, bbox_inches_restore, fixed_dpi=None):
+ """
+ A function that needs to be called when figure dpi changes during the
+ drawing (e.g., rasterizing). It recovers the bbox and re-adjust it with
+ the new dpi.
+ """
+
+ bbox_inches, restore_bbox = bbox_inches_restore
+ restore_bbox()
+ r = adjust_bbox(fig, bbox_inches, fixed_dpi)
+
+ return bbox_inches, r
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_tight_layout.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_tight_layout.py
new file mode 100644
index 0000000000000000000000000000000000000000..548da79fff04320193a7170d5cf0f9b9fa743c0a
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/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/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_tri.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_tri.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..a0c710fc2309fbfac3f37297eda919d86de32c76
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/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/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_type1font.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_type1font.py
new file mode 100644
index 0000000000000000000000000000000000000000..b3e08f52c035e65837e489bf79da60d28e3ac0a8
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_type1font.py
@@ -0,0 +1,879 @@
+"""
+A class representing a Type 1 font.
+
+This version reads pfa and pfb files and splits them for embedding in
+pdf files. It also supports SlantFont and ExtendFont transformations,
+similarly to pdfTeX and friends. There is no support yet for subsetting.
+
+Usage::
+
+ font = Type1Font(filename)
+ clear_part, encrypted_part, finale = font.parts
+ slanted_font = font.transform({'slant': 0.167})
+ extended_font = font.transform({'extend': 1.2})
+
+Sources:
+
+* Adobe Technical Note #5040, Supporting Downloadable PostScript
+ Language Fonts.
+
+* Adobe Type 1 Font Format, Adobe Systems Incorporated, third printing,
+ v1.1, 1993. ISBN 0-201-57044-0.
+"""
+
+from __future__ import annotations
+
+import binascii
+import functools
+import logging
+import re
+import string
+import struct
+import typing as T
+
+import numpy as np
+
+from matplotlib.cbook import _format_approx
+from . import _api
+
+_log = logging.getLogger(__name__)
+
+
+class _Token:
+ """
+ A token in a PostScript stream.
+
+ Attributes
+ ----------
+ pos : int
+ Position, i.e. offset from the beginning of the data.
+ raw : str
+ Raw text of the token.
+ kind : str
+ Description of the token (for debugging or testing).
+ """
+ __slots__ = ('pos', 'raw')
+ kind = '?'
+
+ def __init__(self, pos, raw):
+ _log.debug('type1font._Token %s at %d: %r', self.kind, pos, raw)
+ self.pos = pos
+ self.raw = raw
+
+ def __str__(self):
+ return f"<{self.kind} {self.raw} @{self.pos}>"
+
+ def endpos(self):
+ """Position one past the end of the token"""
+ return self.pos + len(self.raw)
+
+ def is_keyword(self, *names):
+ """Is this a name token with one of the names?"""
+ return False
+
+ def is_slash_name(self):
+ """Is this a name token that starts with a slash?"""
+ return False
+
+ def is_delim(self):
+ """Is this a delimiter token?"""
+ return False
+
+ def is_number(self):
+ """Is this a number token?"""
+ return False
+
+ def value(self):
+ return self.raw
+
+
+class _NameToken(_Token):
+ kind = 'name'
+
+ def is_slash_name(self):
+ return self.raw.startswith('/')
+
+ def value(self):
+ return self.raw[1:]
+
+
+class _BooleanToken(_Token):
+ kind = 'boolean'
+
+ def value(self):
+ return self.raw == 'true'
+
+
+class _KeywordToken(_Token):
+ kind = 'keyword'
+
+ def is_keyword(self, *names):
+ return self.raw in names
+
+
+class _DelimiterToken(_Token):
+ kind = 'delimiter'
+
+ def is_delim(self):
+ return True
+
+ def opposite(self):
+ return {'[': ']', ']': '[',
+ '{': '}', '}': '{',
+ '<<': '>>', '>>': '<<'
+ }[self.raw]
+
+
+class _WhitespaceToken(_Token):
+ kind = 'whitespace'
+
+
+class _StringToken(_Token):
+ kind = 'string'
+ _escapes_re = re.compile(r'\\([\\()nrtbf]|[0-7]{1,3})')
+ _replacements = {'\\': '\\', '(': '(', ')': ')', 'n': '\n',
+ 'r': '\r', 't': '\t', 'b': '\b', 'f': '\f'}
+ _ws_re = re.compile('[\0\t\r\f\n ]')
+
+ @classmethod
+ def _escape(cls, match):
+ group = match.group(1)
+ try:
+ return cls._replacements[group]
+ except KeyError:
+ return chr(int(group, 8))
+
+ @functools.lru_cache
+ def value(self):
+ if self.raw[0] == '(':
+ return self._escapes_re.sub(self._escape, self.raw[1:-1])
+ else:
+ data = self._ws_re.sub('', self.raw[1:-1])
+ if len(data) % 2 == 1:
+ data += '0'
+ return binascii.unhexlify(data)
+
+
+class _BinaryToken(_Token):
+ kind = 'binary'
+
+ def value(self):
+ return self.raw[1:]
+
+
+class _NumberToken(_Token):
+ kind = 'number'
+
+ def is_number(self):
+ return True
+
+ def value(self):
+ if '.' not in self.raw:
+ return int(self.raw)
+ else:
+ return float(self.raw)
+
+
+def _tokenize(data: bytes, skip_ws: bool) -> T.Generator[_Token, int, None]:
+ """
+ A generator that produces _Token instances from Type-1 font code.
+
+ The consumer of the generator may send an integer to the tokenizer to
+ indicate that the next token should be _BinaryToken of the given length.
+
+ Parameters
+ ----------
+ data : bytes
+ The data of the font to tokenize.
+
+ skip_ws : bool
+ If true, the generator will drop any _WhitespaceTokens from the output.
+ """
+
+ text = data.decode('ascii', 'replace')
+ whitespace_or_comment_re = re.compile(r'[\0\t\r\f\n ]+|%[^\r\n]*')
+ token_re = re.compile(r'/{0,2}[^]\0\t\r\f\n ()<>{}/%[]+')
+ instring_re = re.compile(r'[()\\]')
+ hex_re = re.compile(r'^<[0-9a-fA-F\0\t\r\f\n ]*>$')
+ oct_re = re.compile(r'[0-7]{1,3}')
+ pos = 0
+ next_binary: int | None = None
+
+ while pos < len(text):
+ if next_binary is not None:
+ n = next_binary
+ next_binary = (yield _BinaryToken(pos, data[pos:pos+n]))
+ pos += n
+ continue
+ match = whitespace_or_comment_re.match(text, pos)
+ if match:
+ if not skip_ws:
+ next_binary = (yield _WhitespaceToken(pos, match.group()))
+ pos = match.end()
+ elif text[pos] == '(':
+ # PostScript string rules:
+ # - parentheses must be balanced
+ # - backslashes escape backslashes and parens
+ # - also codes \n\r\t\b\f and octal escapes are recognized
+ # - other backslashes do not escape anything
+ start = pos
+ pos += 1
+ depth = 1
+ while depth:
+ match = instring_re.search(text, pos)
+ if match is None:
+ raise ValueError(
+ f'Unterminated string starting at {start}')
+ pos = match.end()
+ if match.group() == '(':
+ depth += 1
+ elif match.group() == ')':
+ depth -= 1
+ else: # a backslash
+ char = text[pos]
+ if char in r'\()nrtbf':
+ pos += 1
+ else:
+ octal = oct_re.match(text, pos)
+ if octal:
+ pos = octal.end()
+ else:
+ pass # non-escaping backslash
+ next_binary = (yield _StringToken(start, text[start:pos]))
+ elif text[pos:pos + 2] in ('<<', '>>'):
+ next_binary = (yield _DelimiterToken(pos, text[pos:pos + 2]))
+ pos += 2
+ elif text[pos] == '<':
+ start = pos
+ try:
+ pos = text.index('>', pos) + 1
+ except ValueError as e:
+ raise ValueError(f'Unterminated hex string starting at {start}'
+ ) from e
+ if not hex_re.match(text[start:pos]):
+ raise ValueError(f'Malformed hex string starting at {start}')
+ next_binary = (yield _StringToken(pos, text[start:pos]))
+ else:
+ match = token_re.match(text, pos)
+ if match:
+ raw = match.group()
+ if raw.startswith('/'):
+ next_binary = (yield _NameToken(pos, raw))
+ elif match.group() in ('true', 'false'):
+ next_binary = (yield _BooleanToken(pos, raw))
+ else:
+ try:
+ float(raw)
+ next_binary = (yield _NumberToken(pos, raw))
+ except ValueError:
+ next_binary = (yield _KeywordToken(pos, raw))
+ pos = match.end()
+ else:
+ next_binary = (yield _DelimiterToken(pos, text[pos]))
+ pos += 1
+
+
+class _BalancedExpression(_Token):
+ pass
+
+
+def _expression(initial, tokens, data):
+ """
+ Consume some number of tokens and return a balanced PostScript expression.
+
+ Parameters
+ ----------
+ initial : _Token
+ The token that triggered parsing a balanced expression.
+ tokens : iterator of _Token
+ Following tokens.
+ data : bytes
+ Underlying data that the token positions point to.
+
+ Returns
+ -------
+ _BalancedExpression
+ """
+ delim_stack = []
+ token = initial
+ while True:
+ if token.is_delim():
+ if token.raw in ('[', '{'):
+ delim_stack.append(token)
+ elif token.raw in (']', '}'):
+ if not delim_stack:
+ raise RuntimeError(f"unmatched closing token {token}")
+ match = delim_stack.pop()
+ if match.raw != token.opposite():
+ raise RuntimeError(
+ f"opening token {match} closed by {token}"
+ )
+ if not delim_stack:
+ break
+ else:
+ raise RuntimeError(f'unknown delimiter {token}')
+ elif not delim_stack:
+ break
+ token = next(tokens)
+ return _BalancedExpression(
+ initial.pos,
+ data[initial.pos:token.endpos()].decode('ascii', 'replace')
+ )
+
+
+class Type1Font:
+ """
+ A class representing a Type-1 font, for use by backends.
+
+ Attributes
+ ----------
+ parts : tuple
+ A 3-tuple of the cleartext part, the encrypted part, and the finale of
+ zeros.
+
+ decrypted : bytes
+ The decrypted form of ``parts[1]``.
+
+ prop : dict[str, Any]
+ A dictionary of font properties. Noteworthy keys include:
+
+ - FontName: PostScript name of the font
+ - Encoding: dict from numeric codes to glyph names
+ - FontMatrix: bytes object encoding a matrix
+ - UniqueID: optional font identifier, dropped when modifying the font
+ - CharStrings: dict from glyph names to byte code
+ - Subrs: array of byte code subroutines
+ - OtherSubrs: bytes object encoding some PostScript code
+ """
+ __slots__ = ('parts', 'decrypted', 'prop', '_pos', '_abbr')
+ # the _pos dict contains (begin, end) indices to parts[0] + decrypted
+ # so that they can be replaced when transforming the font;
+ # but since sometimes a definition appears in both parts[0] and decrypted,
+ # _pos[name] is an array of such pairs
+ #
+ # _abbr maps three standard abbreviations to their particular names in
+ # this font (e.g. 'RD' is named '-|' in some fonts)
+
+ def __init__(self, input):
+ """
+ Initialize a Type-1 font.
+
+ Parameters
+ ----------
+ input : str or 3-tuple
+ Either a pfb file name, or a 3-tuple of already-decoded Type-1
+ font `~.Type1Font.parts`.
+ """
+ if isinstance(input, tuple) and len(input) == 3:
+ self.parts = input
+ else:
+ with open(input, 'rb') as file:
+ data = self._read(file)
+ self.parts = self._split(data)
+
+ self.decrypted = self._decrypt(self.parts[1], 'eexec')
+ self._abbr = {'RD': 'RD', 'ND': 'ND', 'NP': 'NP'}
+ self._parse()
+
+ def _read(self, file):
+ """Read the font from a file, decoding into usable parts."""
+ rawdata = file.read()
+ if not rawdata.startswith(b'\x80'):
+ return rawdata
+
+ data = b''
+ while rawdata:
+ if not rawdata.startswith(b'\x80'):
+ raise RuntimeError('Broken pfb file (expected byte 128, '
+ 'got %d)' % rawdata[0])
+ type = rawdata[1]
+ if type in (1, 2):
+ length, = struct.unpack('> 8))
+ key = ((key+byte) * 52845 + 22719) & 0xffff
+
+ return bytes(plaintext[ndiscard:])
+
+ @staticmethod
+ def _encrypt(plaintext, key, ndiscard=4):
+ """
+ Encrypt plaintext using the Type-1 font algorithm.
+
+ The algorithm is described in Adobe's "Adobe Type 1 Font Format".
+ The key argument can be an integer, or one of the strings
+ 'eexec' and 'charstring', which map to the key specified for the
+ corresponding part of Type-1 fonts.
+
+ The ndiscard argument should be an integer, usually 4. That
+ number of bytes is prepended to the plaintext before encryption.
+ This function prepends NUL bytes for reproducibility, even though
+ the original algorithm uses random bytes, presumably to avoid
+ cryptanalysis.
+ """
+
+ key = _api.check_getitem({'eexec': 55665, 'charstring': 4330}, key=key)
+ ciphertext = []
+ for byte in b'\0' * ndiscard + plaintext:
+ c = byte ^ (key >> 8)
+ ciphertext.append(c)
+ key = ((key + c) * 52845 + 22719) & 0xffff
+
+ return bytes(ciphertext)
+
+ def _parse(self):
+ """
+ Find the values of various font properties. This limited kind
+ of parsing is described in Chapter 10 "Adobe Type Manager
+ Compatibility" of the Type-1 spec.
+ """
+ # Start with reasonable defaults
+ prop = {'Weight': 'Regular', 'ItalicAngle': 0.0, 'isFixedPitch': False,
+ 'UnderlinePosition': -100, 'UnderlineThickness': 50}
+ pos = {}
+ data = self.parts[0] + self.decrypted
+
+ source = _tokenize(data, True)
+ while True:
+ # See if there is a key to be assigned a value
+ # e.g. /FontName in /FontName /Helvetica def
+ try:
+ token = next(source)
+ except StopIteration:
+ break
+ if token.is_delim():
+ # skip over this - we want top-level keys only
+ _expression(token, source, data)
+ if token.is_slash_name():
+ key = token.value()
+ keypos = token.pos
+ else:
+ continue
+
+ # Some values need special parsing
+ if key in ('Subrs', 'CharStrings', 'Encoding', 'OtherSubrs'):
+ prop[key], endpos = {
+ 'Subrs': self._parse_subrs,
+ 'CharStrings': self._parse_charstrings,
+ 'Encoding': self._parse_encoding,
+ 'OtherSubrs': self._parse_othersubrs
+ }[key](source, data)
+ pos.setdefault(key, []).append((keypos, endpos))
+ continue
+
+ try:
+ token = next(source)
+ except StopIteration:
+ break
+
+ if isinstance(token, _KeywordToken):
+ # constructs like
+ # FontDirectory /Helvetica known {...} {...} ifelse
+ # mean the key was not really a key
+ continue
+
+ if token.is_delim():
+ value = _expression(token, source, data).raw
+ else:
+ value = token.value()
+
+ # look for a 'def' possibly preceded by access modifiers
+ try:
+ kw = next(
+ kw for kw in source
+ if not kw.is_keyword('readonly', 'noaccess', 'executeonly')
+ )
+ except StopIteration:
+ break
+
+ # sometimes noaccess def and readonly def are abbreviated
+ if kw.is_keyword('def', self._abbr['ND'], self._abbr['NP']):
+ prop[key] = value
+ pos.setdefault(key, []).append((keypos, kw.endpos()))
+
+ # detect the standard abbreviations
+ if value == '{noaccess def}':
+ self._abbr['ND'] = key
+ elif value == '{noaccess put}':
+ self._abbr['NP'] = key
+ elif value == '{string currentfile exch readstring pop}':
+ self._abbr['RD'] = key
+
+ # Fill in the various *Name properties
+ if 'FontName' not in prop:
+ prop['FontName'] = (prop.get('FullName') or
+ prop.get('FamilyName') or
+ 'Unknown')
+ if 'FullName' not in prop:
+ prop['FullName'] = prop['FontName']
+ if 'FamilyName' not in prop:
+ extras = ('(?i)([ -](regular|plain|italic|oblique|(semi)?bold|'
+ '(ultra)?light|extra|condensed))+$')
+ prop['FamilyName'] = re.sub(extras, '', prop['FullName'])
+ # Decrypt the encrypted parts
+ ndiscard = prop.get('lenIV', 4)
+ cs = prop['CharStrings']
+ for key, value in cs.items():
+ cs[key] = self._decrypt(value, 'charstring', ndiscard)
+ if 'Subrs' in prop:
+ prop['Subrs'] = [
+ self._decrypt(value, 'charstring', ndiscard)
+ for value in prop['Subrs']
+ ]
+
+ self.prop = prop
+ self._pos = pos
+
+ def _parse_subrs(self, tokens, _data):
+ count_token = next(tokens)
+ if not count_token.is_number():
+ raise RuntimeError(
+ f"Token following /Subrs must be a number, was {count_token}"
+ )
+ count = count_token.value()
+ array = [None] * count
+ next(t for t in tokens if t.is_keyword('array'))
+ for _ in range(count):
+ next(t for t in tokens if t.is_keyword('dup'))
+ index_token = next(tokens)
+ if not index_token.is_number():
+ raise RuntimeError(
+ "Token following dup in Subrs definition must be a "
+ f"number, was {index_token}"
+ )
+ nbytes_token = next(tokens)
+ if not nbytes_token.is_number():
+ raise RuntimeError(
+ "Second token following dup in Subrs definition must "
+ f"be a number, was {nbytes_token}"
+ )
+ token = next(tokens)
+ if not token.is_keyword(self._abbr['RD']):
+ raise RuntimeError(
+ f"Token preceding subr must be {self._abbr['RD']}, "
+ f"was {token}"
+ )
+ binary_token = tokens.send(1+nbytes_token.value())
+ array[index_token.value()] = binary_token.value()
+
+ return array, next(tokens).endpos()
+
+ @staticmethod
+ def _parse_charstrings(tokens, _data):
+ count_token = next(tokens)
+ if not count_token.is_number():
+ raise RuntimeError(
+ "Token following /CharStrings must be a number, "
+ f"was {count_token}"
+ )
+ count = count_token.value()
+ charstrings = {}
+ next(t for t in tokens if t.is_keyword('begin'))
+ while True:
+ token = next(t for t in tokens
+ if t.is_keyword('end') or t.is_slash_name())
+ if token.raw == 'end':
+ return charstrings, token.endpos()
+ glyphname = token.value()
+ nbytes_token = next(tokens)
+ if not nbytes_token.is_number():
+ raise RuntimeError(
+ f"Token following /{glyphname} in CharStrings definition "
+ f"must be a number, was {nbytes_token}"
+ )
+ next(tokens) # usually RD or |-
+ binary_token = tokens.send(1+nbytes_token.value())
+ charstrings[glyphname] = binary_token.value()
+
+ @staticmethod
+ def _parse_encoding(tokens, _data):
+ # this only works for encodings that follow the Adobe manual
+ # but some old fonts include non-compliant data - we log a warning
+ # and return a possibly incomplete encoding
+ encoding = {}
+ while True:
+ token = next(t for t in tokens
+ if t.is_keyword('StandardEncoding', 'dup', 'def'))
+ if token.is_keyword('StandardEncoding'):
+ return _StandardEncoding, token.endpos()
+ if token.is_keyword('def'):
+ return encoding, token.endpos()
+ index_token = next(tokens)
+ if not index_token.is_number():
+ _log.warning(
+ f"Parsing encoding: expected number, got {index_token}"
+ )
+ continue
+ name_token = next(tokens)
+ if not name_token.is_slash_name():
+ _log.warning(
+ f"Parsing encoding: expected slash-name, got {name_token}"
+ )
+ continue
+ encoding[index_token.value()] = name_token.value()
+
+ @staticmethod
+ def _parse_othersubrs(tokens, data):
+ init_pos = None
+ while True:
+ token = next(tokens)
+ if init_pos is None:
+ init_pos = token.pos
+ if token.is_delim():
+ _expression(token, tokens, data)
+ elif token.is_keyword('def', 'ND', '|-'):
+ return data[init_pos:token.endpos()], token.endpos()
+
+ def transform(self, effects):
+ """
+ Return a new font that is slanted and/or extended.
+
+ Parameters
+ ----------
+ effects : dict
+ A dict with optional entries:
+
+ - 'slant' : float, default: 0
+ Tangent of the angle that the font is to be slanted to the
+ right. Negative values slant to the left.
+ - 'extend' : float, default: 1
+ Scaling factor for the font width. Values less than 1 condense
+ the glyphs.
+
+ Returns
+ -------
+ `Type1Font`
+ """
+ fontname = self.prop['FontName']
+ italicangle = self.prop['ItalicAngle']
+
+ array = [
+ float(x) for x in (self.prop['FontMatrix']
+ .lstrip('[').rstrip(']').split())
+ ]
+ oldmatrix = np.eye(3, 3)
+ oldmatrix[0:3, 0] = array[::2]
+ oldmatrix[0:3, 1] = array[1::2]
+ modifier = np.eye(3, 3)
+
+ if 'slant' in effects:
+ slant = effects['slant']
+ fontname += f'_Slant_{int(1000 * slant)}'
+ italicangle = round(
+ float(italicangle) - np.arctan(slant) / np.pi * 180,
+ 5
+ )
+ modifier[1, 0] = slant
+
+ if 'extend' in effects:
+ extend = effects['extend']
+ fontname += f'_Extend_{int(1000 * extend)}'
+ modifier[0, 0] = extend
+
+ newmatrix = np.dot(modifier, oldmatrix)
+ array[::2] = newmatrix[0:3, 0]
+ array[1::2] = newmatrix[0:3, 1]
+ fontmatrix = (
+ f"[{' '.join(_format_approx(x, 6) for x in array)}]"
+ )
+ replacements = (
+ [(x, f'/FontName/{fontname} def')
+ for x in self._pos['FontName']]
+ + [(x, f'/ItalicAngle {italicangle} def')
+ for x in self._pos['ItalicAngle']]
+ + [(x, f'/FontMatrix {fontmatrix} readonly def')
+ for x in self._pos['FontMatrix']]
+ + [(x, '') for x in self._pos.get('UniqueID', [])]
+ )
+
+ data = bytearray(self.parts[0])
+ data.extend(self.decrypted)
+ len0 = len(self.parts[0])
+ for (pos0, pos1), value in sorted(replacements, reverse=True):
+ data[pos0:pos1] = value.encode('ascii', 'replace')
+ if pos0 < len(self.parts[0]):
+ if pos1 >= len(self.parts[0]):
+ raise RuntimeError(
+ f"text to be replaced with {value} spans "
+ "the eexec boundary"
+ )
+ len0 += len(value) - pos1 + pos0
+
+ data = bytes(data)
+ return Type1Font((
+ data[:len0],
+ self._encrypt(data[len0:], 'eexec'),
+ self.parts[2]
+ ))
+
+
+_StandardEncoding = {
+ **{ord(letter): letter for letter in string.ascii_letters},
+ 0: '.notdef',
+ 32: 'space',
+ 33: 'exclam',
+ 34: 'quotedbl',
+ 35: 'numbersign',
+ 36: 'dollar',
+ 37: 'percent',
+ 38: 'ampersand',
+ 39: 'quoteright',
+ 40: 'parenleft',
+ 41: 'parenright',
+ 42: 'asterisk',
+ 43: 'plus',
+ 44: 'comma',
+ 45: 'hyphen',
+ 46: 'period',
+ 47: 'slash',
+ 48: 'zero',
+ 49: 'one',
+ 50: 'two',
+ 51: 'three',
+ 52: 'four',
+ 53: 'five',
+ 54: 'six',
+ 55: 'seven',
+ 56: 'eight',
+ 57: 'nine',
+ 58: 'colon',
+ 59: 'semicolon',
+ 60: 'less',
+ 61: 'equal',
+ 62: 'greater',
+ 63: 'question',
+ 64: 'at',
+ 91: 'bracketleft',
+ 92: 'backslash',
+ 93: 'bracketright',
+ 94: 'asciicircum',
+ 95: 'underscore',
+ 96: 'quoteleft',
+ 123: 'braceleft',
+ 124: 'bar',
+ 125: 'braceright',
+ 126: 'asciitilde',
+ 161: 'exclamdown',
+ 162: 'cent',
+ 163: 'sterling',
+ 164: 'fraction',
+ 165: 'yen',
+ 166: 'florin',
+ 167: 'section',
+ 168: 'currency',
+ 169: 'quotesingle',
+ 170: 'quotedblleft',
+ 171: 'guillemotleft',
+ 172: 'guilsinglleft',
+ 173: 'guilsinglright',
+ 174: 'fi',
+ 175: 'fl',
+ 177: 'endash',
+ 178: 'dagger',
+ 179: 'daggerdbl',
+ 180: 'periodcentered',
+ 182: 'paragraph',
+ 183: 'bullet',
+ 184: 'quotesinglbase',
+ 185: 'quotedblbase',
+ 186: 'quotedblright',
+ 187: 'guillemotright',
+ 188: 'ellipsis',
+ 189: 'perthousand',
+ 191: 'questiondown',
+ 193: 'grave',
+ 194: 'acute',
+ 195: 'circumflex',
+ 196: 'tilde',
+ 197: 'macron',
+ 198: 'breve',
+ 199: 'dotaccent',
+ 200: 'dieresis',
+ 202: 'ring',
+ 203: 'cedilla',
+ 205: 'hungarumlaut',
+ 206: 'ogonek',
+ 207: 'caron',
+ 208: 'emdash',
+ 225: 'AE',
+ 227: 'ordfeminine',
+ 232: 'Lslash',
+ 233: 'Oslash',
+ 234: 'OE',
+ 235: 'ordmasculine',
+ 241: 'ae',
+ 245: 'dotlessi',
+ 248: 'lslash',
+ 249: 'oslash',
+ 250: 'oe',
+ 251: 'germandbls',
+}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_version.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_version.py
new file mode 100644
index 0000000000000000000000000000000000000000..285772790bb508a1c5ea5e7967a78fe506596f2d
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/_version.py
@@ -0,0 +1 @@
+version = "3.10.7"
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/animation.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/animation.py
new file mode 100644
index 0000000000000000000000000000000000000000..a87f002011249f353bd740363e55a0d32c62bc38
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/animation.py
@@ -0,0 +1,1823 @@
+import abc
+import base64
+import contextlib
+from io import BytesIO, TextIOWrapper
+import itertools
+import logging
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+from tempfile import TemporaryDirectory
+import uuid
+import warnings
+
+import numpy as np
+from PIL import Image
+
+import matplotlib as mpl
+from matplotlib._animation_data import (
+ DISPLAY_TEMPLATE, INCLUDED_FRAMES, JS_INCLUDE, STYLE_INCLUDE)
+from matplotlib import _api, cbook
+import matplotlib.colors as mcolors
+
+_log = logging.getLogger(__name__)
+
+# Process creation flag for subprocess to prevent it raising a terminal
+# window. See for example https://stackoverflow.com/q/24130623/
+subprocess_creation_flags = (
+ subprocess.CREATE_NO_WINDOW if sys.platform == 'win32' else 0)
+
+
+def adjusted_figsize(w, h, dpi, n):
+ """
+ Compute figure size so that pixels are a multiple of n.
+
+ Parameters
+ ----------
+ w, h : float
+ Size in inches.
+
+ dpi : float
+ The dpi.
+
+ n : int
+ The target multiple.
+
+ Returns
+ -------
+ wnew, hnew : float
+ The new figure size in inches.
+ """
+
+ # this maybe simplified if / when we adopt consistent rounding for
+ # pixel size across the whole library
+ def correct_roundoff(x, dpi, n):
+ if int(x*dpi) % n != 0:
+ if int(np.nextafter(x, np.inf)*dpi) % n == 0:
+ x = np.nextafter(x, np.inf)
+ elif int(np.nextafter(x, -np.inf)*dpi) % n == 0:
+ x = np.nextafter(x, -np.inf)
+ return x
+
+ wnew = int(w * dpi / n) * n / dpi
+ hnew = int(h * dpi / n) * n / dpi
+ return correct_roundoff(wnew, dpi, n), correct_roundoff(hnew, dpi, n)
+
+
+class MovieWriterRegistry:
+ """Registry of available writer classes by human readable name."""
+
+ def __init__(self):
+ self._registered = dict()
+
+ def register(self, name):
+ """
+ Decorator for registering a class under a name.
+
+ Example use::
+
+ @registry.register(name)
+ class Foo:
+ pass
+ """
+ def wrapper(writer_cls):
+ self._registered[name] = writer_cls
+ return writer_cls
+ return wrapper
+
+ def is_available(self, name):
+ """
+ Check if given writer is available by name.
+
+ Parameters
+ ----------
+ name : str
+
+ Returns
+ -------
+ bool
+ """
+ try:
+ cls = self._registered[name]
+ except KeyError:
+ return False
+ return cls.isAvailable()
+
+ def __iter__(self):
+ """Iterate over names of available writer class."""
+ for name in self._registered:
+ if self.is_available(name):
+ yield name
+
+ def list(self):
+ """Get a list of available MovieWriters."""
+ return [*self]
+
+ def __getitem__(self, name):
+ """Get an available writer class from its name."""
+ if self.is_available(name):
+ return self._registered[name]
+ raise RuntimeError(f"Requested MovieWriter ({name}) not available")
+
+
+writers = MovieWriterRegistry()
+
+
+class AbstractMovieWriter(abc.ABC):
+ """
+ Abstract base class for writing movies, providing a way to grab frames by
+ calling `~AbstractMovieWriter.grab_frame`.
+
+ `setup` is called to start the process and `finish` is called afterwards.
+ `saving` is provided as a context manager to facilitate this process as ::
+
+ with moviewriter.saving(fig, outfile='myfile.mp4', dpi=100):
+ # Iterate over frames
+ moviewriter.grab_frame(**savefig_kwargs)
+
+ The use of the context manager ensures that `setup` and `finish` are
+ performed as necessary.
+
+ An instance of a concrete subclass of this class can be given as the
+ ``writer`` argument of `Animation.save()`.
+ """
+
+ def __init__(self, fps=5, metadata=None, codec=None, bitrate=None):
+ self.fps = fps
+ self.metadata = metadata if metadata is not None else {}
+ self.codec = mpl._val_or_rc(codec, 'animation.codec')
+ self.bitrate = mpl._val_or_rc(bitrate, 'animation.bitrate')
+
+ @abc.abstractmethod
+ def setup(self, fig, outfile, dpi=None):
+ """
+ Setup for writing the movie file.
+
+ Parameters
+ ----------
+ fig : `~matplotlib.figure.Figure`
+ The figure object that contains the information for frames.
+ outfile : str
+ The filename of the resulting movie file.
+ dpi : float, default: ``fig.dpi``
+ The DPI (or resolution) for the file. This controls the size
+ in pixels of the resulting movie file.
+ """
+ # Check that path is valid
+ Path(outfile).parent.resolve(strict=True)
+ self.outfile = outfile
+ self.fig = fig
+ if dpi is None:
+ dpi = self.fig.dpi
+ self.dpi = dpi
+
+ @property
+ def frame_size(self):
+ """A tuple ``(width, height)`` in pixels of a movie frame."""
+ w, h = self.fig.get_size_inches()
+ return int(w * self.dpi), int(h * self.dpi)
+
+ def _supports_transparency(self):
+ """
+ Whether this writer supports transparency.
+
+ Writers may consult output file type and codec to determine this at runtime.
+ """
+ return False
+
+ @abc.abstractmethod
+ def grab_frame(self, **savefig_kwargs):
+ """
+ Grab the image information from the figure and save as a movie frame.
+
+ All keyword arguments in *savefig_kwargs* are passed on to the
+ `~.Figure.savefig` call that saves the figure. However, several
+ keyword arguments that are supported by `~.Figure.savefig` may not be
+ passed as they are controlled by the MovieWriter:
+
+ - *dpi*, *bbox_inches*: These may not be passed because each frame of the
+ animation much be exactly the same size in pixels.
+ - *format*: This is controlled by the MovieWriter.
+ """
+
+ @abc.abstractmethod
+ def finish(self):
+ """Finish any processing for writing the movie."""
+
+ @contextlib.contextmanager
+ def saving(self, fig, outfile, dpi, *args, **kwargs):
+ """
+ Context manager to facilitate writing the movie file.
+
+ ``*args, **kw`` are any parameters that should be passed to `setup`.
+ """
+ if mpl.rcParams['savefig.bbox'] == 'tight':
+ _log.info("Disabling savefig.bbox = 'tight', as it may cause "
+ "frame size to vary, which is inappropriate for "
+ "animation.")
+
+ # This particular sequence is what contextlib.contextmanager wants
+ self.setup(fig, outfile, dpi, *args, **kwargs)
+ with mpl.rc_context({'savefig.bbox': None}):
+ try:
+ yield self
+ finally:
+ self.finish()
+
+
+class MovieWriter(AbstractMovieWriter):
+ """
+ Base class for writing movies.
+
+ This is a base class for MovieWriter subclasses that write a movie frame
+ data to a pipe. You cannot instantiate this class directly.
+ See examples for how to use its subclasses.
+
+ Attributes
+ ----------
+ frame_format : str
+ The format used in writing frame data, defaults to 'rgba'.
+ fig : `~matplotlib.figure.Figure`
+ The figure to capture data from.
+ This must be provided by the subclasses.
+ """
+
+ # Builtin writer subclasses additionally define the _exec_key and _args_key
+ # attributes, which indicate the rcParams entries where the path to the
+ # executable and additional command-line arguments to the executable are
+ # stored. Third-party writers cannot meaningfully set these as they cannot
+ # extend rcParams with new keys.
+
+ # Pipe-based writers only support RGBA, but file-based ones support more
+ # formats.
+ supported_formats = ["rgba"]
+
+ def __init__(self, fps=5, codec=None, bitrate=None, extra_args=None,
+ metadata=None):
+ """
+ Parameters
+ ----------
+ fps : int, default: 5
+ Movie frame rate (per second).
+ codec : str or None, default: :rc:`animation.codec`
+ The codec to use.
+ bitrate : int, default: :rc:`animation.bitrate`
+ The bitrate of the movie, in kilobits per second. Higher values
+ means higher quality movies, but increase the file size. A value
+ of -1 lets the underlying movie encoder select the bitrate.
+ extra_args : list of str or None, optional
+ Extra command-line arguments passed to the underlying movie encoder. These
+ arguments are passed last to the encoder, just before the filename. The
+ default, None, means to use :rc:`animation.[name-of-encoder]_args` for the
+ builtin writers.
+ metadata : dict[str, str], default: {}
+ A dictionary of keys and values for metadata to include in the
+ output file. Some keys that may be of use include:
+ title, artist, genre, subject, copyright, srcform, comment.
+ """
+ if type(self) is MovieWriter:
+ # TODO MovieWriter is still an abstract class and needs to be
+ # extended with a mixin. This should be clearer in naming
+ # and description. For now, just give a reasonable error
+ # message to users.
+ raise TypeError(
+ 'MovieWriter cannot be instantiated directly. Please use one '
+ 'of its subclasses.')
+
+ super().__init__(fps=fps, metadata=metadata, codec=codec,
+ bitrate=bitrate)
+ self.frame_format = self.supported_formats[0]
+ self.extra_args = extra_args
+
+ def _adjust_frame_size(self):
+ if self.codec == 'h264':
+ wo, ho = self.fig.get_size_inches()
+ w, h = adjusted_figsize(wo, ho, self.dpi, 2)
+ if (wo, ho) != (w, h):
+ self.fig.set_size_inches(w, h, forward=True)
+ _log.info('figure size in inches has been adjusted '
+ 'from %s x %s to %s x %s', wo, ho, w, h)
+ else:
+ w, h = self.fig.get_size_inches()
+ _log.debug('frame size in pixels is %s x %s', *self.frame_size)
+ return w, h
+
+ def setup(self, fig, outfile, dpi=None):
+ # docstring inherited
+ super().setup(fig, outfile, dpi=dpi)
+ self._w, self._h = self._adjust_frame_size()
+ # Run here so that grab_frame() can write the data to a pipe. This
+ # eliminates the need for temp files.
+ self._run()
+
+ def _run(self):
+ # Uses subprocess to call the program for assembling frames into a
+ # movie file. *args* returns the sequence of command line arguments
+ # from a few configuration options.
+ command = self._args()
+ _log.info('MovieWriter._run: running command: %s',
+ cbook._pformat_subprocess(command))
+ PIPE = subprocess.PIPE
+ self._proc = subprocess.Popen(
+ command, stdin=PIPE, stdout=PIPE, stderr=PIPE,
+ creationflags=subprocess_creation_flags)
+
+ def finish(self):
+ """Finish any processing for writing the movie."""
+ out, err = self._proc.communicate()
+ # Use the encoding/errors that universal_newlines would use.
+ out = TextIOWrapper(BytesIO(out)).read()
+ err = TextIOWrapper(BytesIO(err)).read()
+ if out:
+ _log.log(
+ logging.WARNING if self._proc.returncode else logging.DEBUG,
+ "MovieWriter stdout:\n%s", out)
+ if err:
+ _log.log(
+ logging.WARNING if self._proc.returncode else logging.DEBUG,
+ "MovieWriter stderr:\n%s", err)
+ if self._proc.returncode:
+ raise subprocess.CalledProcessError(
+ self._proc.returncode, self._proc.args, out, err)
+
+ def grab_frame(self, **savefig_kwargs):
+ # docstring inherited
+ _validate_grabframe_kwargs(savefig_kwargs)
+ _log.debug('MovieWriter.grab_frame: Grabbing frame.')
+ # Readjust the figure size in case it has been changed by the user.
+ # All frames must have the same size to save the movie correctly.
+ self.fig.set_size_inches(self._w, self._h)
+ # Save the figure data to the sink, using the frame format and dpi.
+ self.fig.savefig(self._proc.stdin, format=self.frame_format,
+ dpi=self.dpi, **savefig_kwargs)
+
+ def _args(self):
+ """Assemble list of encoder-specific command-line arguments."""
+ return NotImplementedError("args needs to be implemented by subclass.")
+
+ @classmethod
+ def bin_path(cls):
+ """
+ Return the binary path to the commandline tool used by a specific
+ subclass. This is a class method so that the tool can be looked for
+ before making a particular MovieWriter subclass available.
+ """
+ return str(mpl.rcParams[cls._exec_key])
+
+ @classmethod
+ def isAvailable(cls):
+ """Return whether a MovieWriter subclass is actually available."""
+ return shutil.which(cls.bin_path()) is not None
+
+
+class FileMovieWriter(MovieWriter):
+ """
+ `MovieWriter` for writing to individual files and stitching at the end.
+
+ This must be sub-classed to be useful.
+ """
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.frame_format = mpl.rcParams['animation.frame_format']
+
+ def setup(self, fig, outfile, dpi=None, frame_prefix=None):
+ """
+ Setup for writing the movie file.
+
+ Parameters
+ ----------
+ fig : `~matplotlib.figure.Figure`
+ The figure to grab the rendered frames from.
+ outfile : str
+ The filename of the resulting movie file.
+ dpi : float, default: ``fig.dpi``
+ The dpi of the output file. This, with the figure size,
+ controls the size in pixels of the resulting movie file.
+ frame_prefix : str, optional
+ The filename prefix to use for temporary files. If *None* (the
+ default), files are written to a temporary directory which is
+ deleted by `finish`; if not *None*, no temporary files are
+ deleted.
+ """
+ # Check that path is valid
+ Path(outfile).parent.resolve(strict=True)
+ self.fig = fig
+ self.outfile = outfile
+ if dpi is None:
+ dpi = self.fig.dpi
+ self.dpi = dpi
+ self._adjust_frame_size()
+
+ if frame_prefix is None:
+ self._tmpdir = TemporaryDirectory()
+ self.temp_prefix = str(Path(self._tmpdir.name, 'tmp'))
+ else:
+ self._tmpdir = None
+ self.temp_prefix = frame_prefix
+ self._frame_counter = 0 # used for generating sequential file names
+ self._temp_paths = list()
+ self.fname_format_str = '%s%%07d.%s'
+
+ def __del__(self):
+ if hasattr(self, '_tmpdir') and self._tmpdir:
+ self._tmpdir.cleanup()
+
+ @property
+ def frame_format(self):
+ """
+ Format (png, jpeg, etc.) to use for saving the frames, which can be
+ decided by the individual subclasses.
+ """
+ return self._frame_format
+
+ @frame_format.setter
+ def frame_format(self, frame_format):
+ if frame_format in self.supported_formats:
+ self._frame_format = frame_format
+ else:
+ _api.warn_external(
+ f"Ignoring file format {frame_format!r} which is not "
+ f"supported by {type(self).__name__}; using "
+ f"{self.supported_formats[0]} instead.")
+ self._frame_format = self.supported_formats[0]
+
+ def _base_temp_name(self):
+ # Generates a template name (without number) given the frame format
+ # for extension and the prefix.
+ return self.fname_format_str % (self.temp_prefix, self.frame_format)
+
+ def grab_frame(self, **savefig_kwargs):
+ # docstring inherited
+ # Creates a filename for saving using basename and counter.
+ _validate_grabframe_kwargs(savefig_kwargs)
+ path = Path(self._base_temp_name() % self._frame_counter)
+ self._temp_paths.append(path) # Record the filename for later use.
+ self._frame_counter += 1 # Ensures each created name is unique.
+ _log.debug('FileMovieWriter.grab_frame: Grabbing frame %d to path=%s',
+ self._frame_counter, path)
+ with open(path, 'wb') as sink: # Save figure to the sink.
+ self.fig.savefig(sink, format=self.frame_format, dpi=self.dpi,
+ **savefig_kwargs)
+
+ def finish(self):
+ # Call run here now that all frame grabbing is done. All temp files
+ # are available to be assembled.
+ try:
+ self._run()
+ super().finish()
+ finally:
+ if self._tmpdir:
+ _log.debug(
+ 'MovieWriter: clearing temporary path=%s', self._tmpdir
+ )
+ self._tmpdir.cleanup()
+
+
+@writers.register('pillow')
+class PillowWriter(AbstractMovieWriter):
+ def _supports_transparency(self):
+ return True
+
+ @classmethod
+ def isAvailable(cls):
+ return True
+
+ def setup(self, fig, outfile, dpi=None):
+ super().setup(fig, outfile, dpi=dpi)
+ self._frames = []
+
+ def grab_frame(self, **savefig_kwargs):
+ _validate_grabframe_kwargs(savefig_kwargs)
+ buf = BytesIO()
+ self.fig.savefig(
+ buf, **{**savefig_kwargs, "format": "rgba", "dpi": self.dpi})
+ im = Image.frombuffer(
+ "RGBA", self.frame_size, buf.getbuffer(), "raw", "RGBA", 0, 1)
+ if im.getextrema()[3][0] < 255:
+ # This frame has transparency, so we'll just add it as is.
+ self._frames.append(im)
+ else:
+ # Without transparency, we switch to RGB mode, which converts to P mode a
+ # little better if needed (specifically, this helps with GIF output.)
+ self._frames.append(im.convert("RGB"))
+
+ def finish(self):
+ self._frames[0].save(
+ self.outfile, save_all=True, append_images=self._frames[1:],
+ duration=int(1000 / self.fps), loop=0)
+
+
+# Base class of ffmpeg information. Has the config keys and the common set
+# of arguments that controls the *output* side of things.
+class FFMpegBase:
+ """
+ Mixin class for FFMpeg output.
+
+ This is a base class for the concrete `FFMpegWriter` and `FFMpegFileWriter`
+ classes.
+ """
+
+ _exec_key = 'animation.ffmpeg_path'
+ _args_key = 'animation.ffmpeg_args'
+
+ def _supports_transparency(self):
+ suffix = Path(self.outfile).suffix
+ if suffix in {'.apng', '.avif', '.gif', '.webm', '.webp'}:
+ return True
+ # This list was found by going through `ffmpeg -codecs` for video encoders,
+ # running them with _support_transparency() forced to True, and checking that
+ # the "Pixel format" in Kdenlive included alpha. Note this is not a guarantee
+ # that transparency will work; you may also need to pass `-pix_fmt`, but we
+ # trust the user has done so if they are asking for these formats.
+ return self.codec in {
+ 'apng', 'avrp', 'bmp', 'cfhd', 'dpx', 'ffv1', 'ffvhuff', 'gif', 'huffyuv',
+ 'jpeg2000', 'ljpeg', 'png', 'prores', 'prores_aw', 'prores_ks', 'qtrle',
+ 'rawvideo', 'targa', 'tiff', 'utvideo', 'v408', }
+
+ @property
+ def output_args(self):
+ args = []
+ suffix = Path(self.outfile).suffix
+ if suffix in {'.apng', '.avif', '.gif', '.webm', '.webp'}:
+ self.codec = suffix[1:]
+ else:
+ args.extend(['-vcodec', self.codec])
+ extra_args = (self.extra_args if self.extra_args is not None
+ else mpl.rcParams[self._args_key])
+ # For h264, the default format is yuv444p, which is not compatible
+ # with quicktime (and others). Specifying yuv420p fixes playback on
+ # iOS, as well as HTML5 video in firefox and safari (on both Windows and
+ # macOS). Also fixes internet explorer. This is as of 2015/10/29.
+ if self.codec == 'h264' and '-pix_fmt' not in extra_args:
+ args.extend(['-pix_fmt', 'yuv420p'])
+ # For GIF, we're telling FFmpeg to split the video stream, to generate
+ # a palette, and then use it for encoding.
+ elif self.codec == 'gif' and '-filter_complex' not in extra_args:
+ args.extend(['-filter_complex',
+ 'split [a][b];[a] palettegen [p];[b][p] paletteuse'])
+ # For AVIF, we're telling FFmpeg to split the video stream, extract the alpha,
+ # in order to place it in a secondary stream, as needed by AVIF-in-FFmpeg.
+ elif self.codec == 'avif' and '-filter_complex' not in extra_args:
+ args.extend(['-filter_complex',
+ 'split [rgb][rgba]; [rgba] alphaextract [alpha]',
+ '-map', '[rgb]', '-map', '[alpha]'])
+ if self.bitrate > 0:
+ args.extend(['-b', '%dk' % self.bitrate]) # %dk: bitrate in kbps.
+ for k, v in self.metadata.items():
+ args.extend(['-metadata', f'{k}={v}'])
+ args.extend(extra_args)
+
+ return args + ['-y', self.outfile]
+
+
+# Combine FFMpeg options with pipe-based writing
+@writers.register('ffmpeg')
+class FFMpegWriter(FFMpegBase, MovieWriter):
+ """
+ Pipe-based ffmpeg writer.
+
+ Frames are streamed directly to ffmpeg via a pipe and written in a single pass.
+
+ This effectively works as a slideshow input to ffmpeg with the fps passed as
+ ``-framerate``, so see also `their notes on frame rates`_ for further details.
+
+ .. _their notes on frame rates: https://trac.ffmpeg.org/wiki/Slideshow#Framerates
+ """
+ def _args(self):
+ # Returns the command line parameters for subprocess to use
+ # ffmpeg to create a movie using a pipe.
+ args = [self.bin_path(), '-f', 'rawvideo', '-vcodec', 'rawvideo',
+ '-s', '%dx%d' % self.frame_size, '-pix_fmt', self.frame_format,
+ '-framerate', str(self.fps)]
+ # Logging is quieted because subprocess.PIPE has limited buffer size.
+ # If you have a lot of frames in your animation and set logging to
+ # DEBUG, you will have a buffer overrun.
+ if _log.getEffectiveLevel() > logging.DEBUG:
+ args += ['-loglevel', 'error']
+ args += ['-i', 'pipe:'] + self.output_args
+ return args
+
+
+# Combine FFMpeg options with temp file-based writing
+@writers.register('ffmpeg_file')
+class FFMpegFileWriter(FFMpegBase, FileMovieWriter):
+ """
+ File-based ffmpeg writer.
+
+ Frames are written to temporary files on disk and then stitched together at the end.
+
+ This effectively works as a slideshow input to ffmpeg with the fps passed as
+ ``-framerate``, so see also `their notes on frame rates`_ for further details.
+
+ .. _their notes on frame rates: https://trac.ffmpeg.org/wiki/Slideshow#Framerates
+ """
+ supported_formats = ['png', 'jpeg', 'tiff', 'raw', 'rgba']
+
+ def _args(self):
+ # Returns the command line parameters for subprocess to use
+ # ffmpeg to create a movie using a collection of temp images
+ args = []
+ # For raw frames, we need to explicitly tell ffmpeg the metadata.
+ if self.frame_format in {'raw', 'rgba'}:
+ args += [
+ '-f', 'image2', '-vcodec', 'rawvideo',
+ '-video_size', '%dx%d' % self.frame_size,
+ '-pixel_format', 'rgba',
+ ]
+ args += ['-framerate', str(self.fps), '-i', self._base_temp_name()]
+ if not self._tmpdir:
+ args += ['-frames:v', str(self._frame_counter)]
+ # Logging is quieted because subprocess.PIPE has limited buffer size.
+ # If you have a lot of frames in your animation and set logging to
+ # DEBUG, you will have a buffer overrun.
+ if _log.getEffectiveLevel() > logging.DEBUG:
+ args += ['-loglevel', 'error']
+ return [self.bin_path(), *args, *self.output_args]
+
+
+# Base class for animated GIFs with ImageMagick
+class ImageMagickBase:
+ """
+ Mixin class for ImageMagick output.
+
+ This is a base class for the concrete `ImageMagickWriter` and
+ `ImageMagickFileWriter` classes, which define an ``input_names`` attribute
+ (or property) specifying the input names passed to ImageMagick.
+ """
+
+ _exec_key = 'animation.convert_path'
+ _args_key = 'animation.convert_args'
+
+ def _supports_transparency(self):
+ suffix = Path(self.outfile).suffix
+ return suffix in {'.apng', '.avif', '.gif', '.webm', '.webp'}
+
+ def _args(self):
+ # ImageMagick does not recognize "raw".
+ fmt = "rgba" if self.frame_format == "raw" else self.frame_format
+ extra_args = (self.extra_args if self.extra_args is not None
+ else mpl.rcParams[self._args_key])
+ return [
+ self.bin_path(),
+ "-size", "%ix%i" % self.frame_size,
+ "-depth", "8",
+ "-delay", str(100 / self.fps),
+ "-loop", "0",
+ f"{fmt}:{self.input_names}",
+ *extra_args,
+ self.outfile,
+ ]
+
+ @classmethod
+ def bin_path(cls):
+ binpath = super().bin_path()
+ if binpath == 'convert':
+ binpath = mpl._get_executable_info('magick').executable
+ return binpath
+
+ @classmethod
+ def isAvailable(cls):
+ try:
+ return super().isAvailable()
+ except mpl.ExecutableNotFoundError as _enf:
+ # May be raised by get_executable_info.
+ _log.debug('ImageMagick unavailable due to: %s', _enf)
+ return False
+
+
+# Combine ImageMagick options with pipe-based writing
+@writers.register('imagemagick')
+class ImageMagickWriter(ImageMagickBase, MovieWriter):
+ """
+ Pipe-based animated gif writer.
+
+ Frames are streamed directly to ImageMagick via a pipe and written
+ in a single pass.
+ """
+
+ input_names = "-" # stdin
+
+
+# Combine ImageMagick options with temp file-based writing
+@writers.register('imagemagick_file')
+class ImageMagickFileWriter(ImageMagickBase, FileMovieWriter):
+ """
+ File-based animated gif writer.
+
+ Frames are written to temporary files on disk and then stitched
+ together at the end.
+ """
+
+ supported_formats = ['png', 'jpeg', 'tiff', 'raw', 'rgba']
+ input_names = property(
+ lambda self: f'{self.temp_prefix}*.{self.frame_format}')
+
+
+# Taken directly from jakevdp's JSAnimation package at
+# http://github.com/jakevdp/JSAnimation
+def _included_frames(frame_count, frame_format, frame_dir):
+ return INCLUDED_FRAMES.format(Nframes=frame_count,
+ frame_dir=frame_dir,
+ frame_format=frame_format)
+
+
+def _embedded_frames(frame_list, frame_format):
+ """frame_list should be a list of base64-encoded png files"""
+ if frame_format == 'svg':
+ # Fix MIME type for svg
+ frame_format = 'svg+xml'
+ template = ' frames[{0}] = "data:image/{1};base64,{2}"\n'
+ return "\n" + "".join(
+ template.format(i, frame_format, frame_data.replace('\n', '\\\n'))
+ for i, frame_data in enumerate(frame_list))
+
+
+@writers.register('html')
+class HTMLWriter(FileMovieWriter):
+ """Writer for JavaScript-based HTML movies."""
+
+ supported_formats = ['png', 'jpeg', 'tiff', 'svg']
+
+ @classmethod
+ def isAvailable(cls):
+ return True
+
+ def __init__(self, fps=30, codec=None, bitrate=None, extra_args=None,
+ metadata=None, embed_frames=False, default_mode='loop',
+ embed_limit=None):
+
+ if extra_args:
+ _log.warning("HTMLWriter ignores 'extra_args'")
+ extra_args = () # Don't lookup nonexistent rcParam[args_key].
+ self.embed_frames = embed_frames
+ self.default_mode = default_mode.lower()
+ _api.check_in_list(['loop', 'once', 'reflect'],
+ default_mode=self.default_mode)
+
+ # Save embed limit, which is given in MB
+ self._bytes_limit = mpl._val_or_rc(embed_limit, 'animation.embed_limit')
+ # Convert from MB to bytes
+ self._bytes_limit *= 1024 * 1024
+
+ super().__init__(fps, codec, bitrate, extra_args, metadata)
+
+ def setup(self, fig, outfile, dpi=None, frame_dir=None):
+ outfile = Path(outfile)
+ _api.check_in_list(['.html', '.htm'], outfile_extension=outfile.suffix)
+
+ self._saved_frames = []
+ self._total_bytes = 0
+ self._hit_limit = False
+
+ if not self.embed_frames:
+ if frame_dir is None:
+ frame_dir = outfile.with_name(outfile.stem + '_frames')
+ frame_dir.mkdir(parents=True, exist_ok=True)
+ frame_prefix = frame_dir / 'frame'
+ else:
+ frame_prefix = None
+
+ super().setup(fig, outfile, dpi, frame_prefix)
+ self._clear_temp = False
+
+ def grab_frame(self, **savefig_kwargs):
+ _validate_grabframe_kwargs(savefig_kwargs)
+ if self.embed_frames:
+ # Just stop processing if we hit the limit
+ if self._hit_limit:
+ return
+ f = BytesIO()
+ self.fig.savefig(f, format=self.frame_format,
+ dpi=self.dpi, **savefig_kwargs)
+ imgdata64 = base64.encodebytes(f.getvalue()).decode('ascii')
+ self._total_bytes += len(imgdata64)
+ if self._total_bytes >= self._bytes_limit:
+ _log.warning(
+ "Animation size has reached %s bytes, exceeding the limit "
+ "of %s. If you're sure you want a larger animation "
+ "embedded, set the animation.embed_limit rc parameter to "
+ "a larger value (in MB). This and further frames will be "
+ "dropped.", self._total_bytes, self._bytes_limit)
+ self._hit_limit = True
+ else:
+ self._saved_frames.append(imgdata64)
+ else:
+ return super().grab_frame(**savefig_kwargs)
+
+ def finish(self):
+ # save the frames to an html file
+ if self.embed_frames:
+ fill_frames = _embedded_frames(self._saved_frames,
+ self.frame_format)
+ frame_count = len(self._saved_frames)
+ else:
+ # temp names is filled by FileMovieWriter
+ frame_count = len(self._temp_paths)
+ fill_frames = _included_frames(
+ frame_count, self.frame_format,
+ self._temp_paths[0].parent.relative_to(self.outfile.parent))
+ mode_dict = dict(once_checked='',
+ loop_checked='',
+ reflect_checked='')
+ mode_dict[self.default_mode + '_checked'] = 'checked'
+
+ interval = 1000 // self.fps
+
+ with open(self.outfile, 'w') as of:
+ of.write(JS_INCLUDE + STYLE_INCLUDE)
+ of.write(DISPLAY_TEMPLATE.format(id=uuid.uuid4().hex,
+ Nframes=frame_count,
+ fill_frames=fill_frames,
+ interval=interval,
+ **mode_dict))
+
+ # Duplicate the temporary file clean up logic from
+ # FileMovieWriter.finish. We cannot call the inherited version of
+ # finish because it assumes that there is a subprocess that we either
+ # need to call to merge many frames together or that there is a
+ # subprocess call that we need to clean up.
+ if self._tmpdir:
+ _log.debug('MovieWriter: clearing temporary path=%s', self._tmpdir)
+ self._tmpdir.cleanup()
+
+
+class Animation:
+ """
+ A base class for Animations.
+
+ This class is not usable as is, and should be subclassed to provide needed
+ behavior.
+
+ .. note::
+
+ You must store the created Animation in a variable that lives as long
+ as the animation should run. Otherwise, the Animation object will be
+ garbage-collected and the animation stops.
+
+ Parameters
+ ----------
+ fig : `~matplotlib.figure.Figure`
+ The figure object used to get needed events, such as draw or resize.
+
+ event_source : object, optional
+ A class that can run a callback when desired events
+ are generated, as well as be stopped and started.
+
+ Examples include timers (see `TimedAnimation`) and file
+ system notifications.
+
+ blit : bool, default: False
+ Whether blitting is used to optimize drawing. If the backend does not
+ support blitting, then this parameter has no effect.
+
+ See Also
+ --------
+ FuncAnimation, ArtistAnimation
+ """
+
+ def __init__(self, fig, event_source=None, blit=False):
+ self._draw_was_started = False
+
+ self._fig = fig
+ # Disables blitting for backends that don't support it. This
+ # allows users to request it if available, but still have a
+ # fallback that works if it is not.
+ self._blit = blit and fig.canvas.supports_blit
+
+ # These are the basics of the animation. The frame sequence represents
+ # information for each frame of the animation and depends on how the
+ # drawing is handled by the subclasses. The event source fires events
+ # that cause the frame sequence to be iterated.
+ self.frame_seq = self.new_frame_seq()
+ self.event_source = event_source
+
+ # Instead of starting the event source now, we connect to the figure's
+ # draw_event, so that we only start once the figure has been drawn.
+ self._first_draw_id = fig.canvas.mpl_connect('draw_event', self._start)
+
+ # Connect to the figure's close_event so that we don't continue to
+ # fire events and try to draw to a deleted figure.
+ self._close_id = self._fig.canvas.mpl_connect('close_event',
+ self._stop)
+ if self._blit:
+ self._setup_blit()
+
+ def __del__(self):
+ if not getattr(self, '_draw_was_started', True):
+ warnings.warn(
+ 'Animation was deleted without rendering anything. This is '
+ 'most likely not intended. To prevent deletion, assign the '
+ 'Animation to a variable, e.g. `anim`, that exists until you '
+ 'output the Animation using `plt.show()` or '
+ '`anim.save()`.'
+ )
+
+ def _start(self, *args):
+ """
+ Starts interactive animation. Adds the draw frame command to the GUI
+ handler, calls show to start the event loop.
+ """
+ # Do not start the event source if saving() it.
+ if self._fig.canvas.is_saving():
+ return
+ # First disconnect our draw event handler
+ self._fig.canvas.mpl_disconnect(self._first_draw_id)
+
+ # Now do any initial draw
+ self._init_draw()
+
+ # Add our callback for stepping the animation and
+ # actually start the event_source.
+ self.event_source.add_callback(self._step)
+ self.event_source.start()
+
+ def _stop(self, *args):
+ # On stop we disconnect all of our events.
+ if self._blit:
+ self._fig.canvas.mpl_disconnect(self._resize_id)
+ self._fig.canvas.mpl_disconnect(self._close_id)
+ self.event_source.remove_callback(self._step)
+ self.event_source = None
+
+ def save(self, filename, writer=None, fps=None, dpi=None, codec=None,
+ bitrate=None, extra_args=None, metadata=None, extra_anim=None,
+ savefig_kwargs=None, *, progress_callback=None):
+ """
+ Save the animation as a movie file by drawing every frame.
+
+ Parameters
+ ----------
+ filename : str
+ The output filename, e.g., :file:`mymovie.mp4`.
+
+ writer : `MovieWriter` or str, default: :rc:`animation.writer`
+ A `MovieWriter` instance to use or a key that identifies a
+ class to use, such as 'ffmpeg'.
+
+ fps : int, optional
+ Movie frame rate (per second). If not set, the frame rate from the
+ animation's frame interval.
+
+ dpi : float, default: :rc:`savefig.dpi`
+ Controls the dots per inch for the movie frames. Together with
+ the figure's size in inches, this controls the size of the movie.
+
+ codec : str, default: :rc:`animation.codec`.
+ The video codec to use. Not all codecs are supported by a given
+ `MovieWriter`.
+
+ bitrate : int, default: :rc:`animation.bitrate`
+ The bitrate of the movie, in kilobits per second. Higher values
+ means higher quality movies, but increase the file size. A value
+ of -1 lets the underlying movie encoder select the bitrate.
+
+ extra_args : list of str or None, optional
+ Extra command-line arguments passed to the underlying movie encoder. These
+ arguments are passed last to the encoder, just before the output filename.
+ The default, None, means to use :rc:`animation.[name-of-encoder]_args` for
+ the builtin writers.
+
+ metadata : dict[str, str], default: {}
+ Dictionary of keys and values for metadata to include in
+ the output file. Some keys that may be of use include:
+ title, artist, genre, subject, copyright, srcform, comment.
+
+ extra_anim : list, default: []
+ Additional `Animation` objects that should be included
+ in the saved movie file. These need to be from the same
+ `.Figure` instance. Also, animation frames will
+ just be simply combined, so there should be a 1:1 correspondence
+ between the frames from the different animations.
+
+ savefig_kwargs : dict, default: {}
+ Keyword arguments passed to each `~.Figure.savefig` call used to
+ save the individual frames.
+
+ progress_callback : function, optional
+ A callback function that will be called for every frame to notify
+ the saving progress. It must have the signature ::
+
+ def func(current_frame: int, total_frames: int) -> Any
+
+ where *current_frame* is the current frame number and *total_frames* is the
+ total number of frames to be saved. *total_frames* is set to None, if the
+ total number of frames cannot be determined. Return values may exist but are
+ ignored.
+
+ Example code to write the progress to stdout::
+
+ progress_callback = lambda i, n: print(f'Saving frame {i}/{n}')
+
+ Notes
+ -----
+ *fps*, *codec*, *bitrate*, *extra_args* and *metadata* are used to
+ construct a `.MovieWriter` instance and can only be passed if
+ *writer* is a string. If they are passed as non-*None* and *writer*
+ is a `.MovieWriter`, a `RuntimeError` will be raised.
+ """
+
+ all_anim = [self]
+ if extra_anim is not None:
+ all_anim.extend(anim for anim in extra_anim
+ if anim._fig is self._fig)
+
+ # Disable "Animation was deleted without rendering" warning.
+ for anim in all_anim:
+ anim._draw_was_started = True
+
+ if writer is None:
+ writer = mpl.rcParams['animation.writer']
+ elif (not isinstance(writer, str) and
+ any(arg is not None
+ for arg in (fps, codec, bitrate, extra_args, metadata))):
+ raise RuntimeError('Passing in values for arguments '
+ 'fps, codec, bitrate, extra_args, or metadata '
+ 'is not supported when writer is an existing '
+ 'MovieWriter instance. These should instead be '
+ 'passed as arguments when creating the '
+ 'MovieWriter instance.')
+
+ if savefig_kwargs is None:
+ savefig_kwargs = {}
+ else:
+ # we are going to mutate this below
+ savefig_kwargs = dict(savefig_kwargs)
+
+ if fps is None and hasattr(self, '_interval'):
+ # Convert interval in ms to frames per second
+ fps = 1000. / self._interval
+
+ # Reuse the savefig DPI for ours if none is given.
+ dpi = mpl._val_or_rc(dpi, 'savefig.dpi')
+ if dpi == 'figure':
+ dpi = self._fig.dpi
+
+ writer_kwargs = {}
+ if codec is not None:
+ writer_kwargs['codec'] = codec
+ if bitrate is not None:
+ writer_kwargs['bitrate'] = bitrate
+ if extra_args is not None:
+ writer_kwargs['extra_args'] = extra_args
+ if metadata is not None:
+ writer_kwargs['metadata'] = metadata
+
+ # If we have the name of a writer, instantiate an instance of the
+ # registered class.
+ if isinstance(writer, str):
+ try:
+ writer_cls = writers[writer]
+ except RuntimeError: # Raised if not available.
+ writer_cls = PillowWriter # Always available.
+ _log.warning("MovieWriter %s unavailable; using Pillow "
+ "instead.", writer)
+ writer = writer_cls(fps, **writer_kwargs)
+ _log.info('Animation.save using %s', type(writer))
+
+ if 'bbox_inches' in savefig_kwargs:
+ _log.warning("Warning: discarding the 'bbox_inches' argument in "
+ "'savefig_kwargs' as it may cause frame size "
+ "to vary, which is inappropriate for animation.")
+ savefig_kwargs.pop('bbox_inches')
+
+ # Create a new sequence of frames for saved data. This is different
+ # from new_frame_seq() to give the ability to save 'live' generated
+ # frame information to be saved later.
+ # TODO: Right now, after closing the figure, saving a movie won't work
+ # since GUI widgets are gone. Either need to remove extra code to
+ # allow for this non-existent use case or find a way to make it work.
+
+ def _pre_composite_to_white(color):
+ r, g, b, a = mcolors.to_rgba(color)
+ return a * np.array([r, g, b]) + 1 - a
+
+ # canvas._is_saving = True makes the draw_event animation-starting
+ # callback a no-op; canvas.manager = None prevents resizing the GUI
+ # widget (both are likewise done in savefig()).
+ with (writer.saving(self._fig, filename, dpi),
+ cbook._setattr_cm(self._fig.canvas, _is_saving=True, manager=None)):
+ if not writer._supports_transparency():
+ facecolor = savefig_kwargs.get('facecolor',
+ mpl.rcParams['savefig.facecolor'])
+ if facecolor == 'auto':
+ facecolor = self._fig.get_facecolor()
+ savefig_kwargs['facecolor'] = _pre_composite_to_white(facecolor)
+ savefig_kwargs['transparent'] = False # just to be safe!
+
+ for anim in all_anim:
+ anim._init_draw() # Clear the initial frame
+ frame_number = 0
+ # TODO: Currently only FuncAnimation has a save_count
+ # attribute. Can we generalize this to all Animations?
+ save_count_list = [getattr(a, '_save_count', None)
+ for a in all_anim]
+ if None in save_count_list:
+ total_frames = None
+ else:
+ total_frames = sum(save_count_list)
+ for data in zip(*[a.new_saved_frame_seq() for a in all_anim]):
+ for anim, d in zip(all_anim, data):
+ # TODO: See if turning off blit is really necessary
+ anim._draw_next_frame(d, blit=False)
+ if progress_callback is not None:
+ progress_callback(frame_number, total_frames)
+ frame_number += 1
+ writer.grab_frame(**savefig_kwargs)
+
+ def _step(self, *args):
+ """
+ Handler for getting events. By default, gets the next frame in the
+ sequence and hands the data off to be drawn.
+ """
+ # Returns True to indicate that the event source should continue to
+ # call _step, until the frame sequence reaches the end of iteration,
+ # at which point False will be returned.
+ try:
+ framedata = next(self.frame_seq)
+ self._draw_next_frame(framedata, self._blit)
+ return True
+ except StopIteration:
+ return False
+
+ def new_frame_seq(self):
+ """Return a new sequence of frame information."""
+ # Default implementation is just an iterator over self._framedata
+ return iter(self._framedata)
+
+ def new_saved_frame_seq(self):
+ """Return a new sequence of saved/cached frame information."""
+ # Default is the same as the regular frame sequence
+ return self.new_frame_seq()
+
+ def _draw_next_frame(self, framedata, blit):
+ # Breaks down the drawing of the next frame into steps of pre- and
+ # post- draw, as well as the drawing of the frame itself.
+ self._pre_draw(framedata, blit)
+ self._draw_frame(framedata)
+ self._post_draw(framedata, blit)
+
+ def _init_draw(self):
+ # Initial draw to clear the frame. Also used by the blitting code
+ # when a clean base is required.
+ self._draw_was_started = True
+
+ def _pre_draw(self, framedata, blit):
+ # Perform any cleaning or whatnot before the drawing of the frame.
+ # This default implementation allows blit to clear the frame.
+ if blit:
+ self._blit_clear(self._drawn_artists)
+
+ def _draw_frame(self, framedata):
+ # Performs actual drawing of the frame.
+ raise NotImplementedError('Needs to be implemented by subclasses to'
+ ' actually make an animation.')
+
+ def _post_draw(self, framedata, blit):
+ # After the frame is rendered, this handles the actual flushing of
+ # the draw, which can be a direct draw_idle() or make use of the
+ # blitting.
+ if blit and self._drawn_artists:
+ self._blit_draw(self._drawn_artists)
+ else:
+ self._fig.canvas.draw_idle()
+
+ # The rest of the code in this class is to facilitate easy blitting
+ def _blit_draw(self, artists):
+ # Handles blitted drawing, which renders only the artists given instead
+ # of the entire figure.
+ updated_ax = {a.axes for a in artists}
+ # Enumerate artists to cache Axes backgrounds. We do not draw
+ # artists yet to not cache foreground from plots with shared Axes
+ for ax in updated_ax:
+ # If we haven't cached the background for the current view of this
+ # Axes object, do so now. This might not always be reliable, but
+ # it's an attempt to automate the process.
+ cur_view = ax._get_view()
+ view, bg = self._blit_cache.get(ax, (object(), None))
+ if cur_view != view:
+ self._blit_cache[ax] = (
+ cur_view, ax.figure.canvas.copy_from_bbox(ax.bbox))
+ # Make a separate pass to draw foreground.
+ for a in artists:
+ a.axes.draw_artist(a)
+ # After rendering all the needed artists, blit each Axes individually.
+ for ax in updated_ax:
+ ax.figure.canvas.blit(ax.bbox)
+
+ def _blit_clear(self, artists):
+ # Get a list of the Axes that need clearing from the artists that
+ # have been drawn. Grab the appropriate saved background from the
+ # cache and restore.
+ axes = {a.axes for a in artists}
+ for ax in axes:
+ try:
+ view, bg = self._blit_cache[ax]
+ except KeyError:
+ continue
+ if ax._get_view() == view:
+ ax.figure.canvas.restore_region(bg)
+ else:
+ self._blit_cache.pop(ax)
+
+ def _setup_blit(self):
+ # Setting up the blit requires: a cache of the background for the Axes
+ self._blit_cache = dict()
+ self._drawn_artists = []
+ # _post_draw needs to be called first to initialize the renderer
+ self._post_draw(None, self._blit)
+ # Then we need to clear the Frame for the initial draw
+ # This is typically handled in _on_resize because QT and Tk
+ # emit a resize event on launch, but the macosx backend does not,
+ # thus we force it here for everyone for consistency
+ self._init_draw()
+ # Connect to future resize events
+ self._resize_id = self._fig.canvas.mpl_connect('resize_event',
+ self._on_resize)
+
+ def _on_resize(self, event):
+ # On resize, we need to disable the resize event handling so we don't
+ # get too many events. Also stop the animation events, so that
+ # we're paused. Reset the cache and re-init. Set up an event handler
+ # to catch once the draw has actually taken place.
+ self._fig.canvas.mpl_disconnect(self._resize_id)
+ self.event_source.stop()
+ self._blit_cache.clear()
+ self._init_draw()
+ self._resize_id = self._fig.canvas.mpl_connect('draw_event',
+ self._end_redraw)
+
+ def _end_redraw(self, event):
+ # Now that the redraw has happened, do the post draw flushing and
+ # blit handling. Then re-enable all of the original events.
+ self._post_draw(None, False)
+ self.event_source.start()
+ self._fig.canvas.mpl_disconnect(self._resize_id)
+ self._resize_id = self._fig.canvas.mpl_connect('resize_event',
+ self._on_resize)
+
+ def to_html5_video(self, embed_limit=None):
+ """
+ Convert the animation to an HTML5 ```` tag.
+
+ This saves the animation as an h264 video, encoded in base64
+ directly into the HTML5 video tag. This respects :rc:`animation.writer`
+ and :rc:`animation.bitrate`. This also makes use of the
+ *interval* to control the speed, and uses the *repeat*
+ parameter to decide whether to loop.
+
+ Parameters
+ ----------
+ embed_limit : float, optional
+ Limit, in MB, of the returned animation. No animation is created
+ if the limit is exceeded.
+ Defaults to :rc:`animation.embed_limit` = 20.0.
+
+ Returns
+ -------
+ str
+ An HTML5 video tag with the animation embedded as base64 encoded
+ h264 video.
+ If the *embed_limit* is exceeded, this returns the string
+ "Video too large to embed."
+ """
+ VIDEO_TAG = r'''
+
+ Your browser does not support the video tag.
+ '''
+ # Cache the rendering of the video as HTML
+ if not hasattr(self, '_base64_video'):
+ # Save embed limit, which is given in MB
+ embed_limit = mpl._val_or_rc(embed_limit, 'animation.embed_limit')
+
+ # Convert from MB to bytes
+ embed_limit *= 1024 * 1024
+
+ # Can't open a NamedTemporaryFile twice on Windows, so use a
+ # TemporaryDirectory instead.
+ with TemporaryDirectory() as tmpdir:
+ path = Path(tmpdir, "temp.m4v")
+ # We create a writer manually so that we can get the
+ # appropriate size for the tag
+ Writer = writers[mpl.rcParams['animation.writer']]
+ writer = Writer(codec='h264',
+ bitrate=mpl.rcParams['animation.bitrate'],
+ fps=1000. / self._interval)
+ self.save(str(path), writer=writer)
+ # Now open and base64 encode.
+ vid64 = base64.encodebytes(path.read_bytes())
+
+ vid_len = len(vid64)
+ if vid_len >= embed_limit:
+ _log.warning(
+ "Animation movie is %s bytes, exceeding the limit of %s. "
+ "If you're sure you want a large animation embedded, set "
+ "the animation.embed_limit rc parameter to a larger value "
+ "(in MB).", vid_len, embed_limit)
+ else:
+ self._base64_video = vid64.decode('ascii')
+ self._video_size = 'width="{}" height="{}"'.format(
+ *writer.frame_size)
+
+ # If we exceeded the size, this attribute won't exist
+ if hasattr(self, '_base64_video'):
+ # Default HTML5 options are to autoplay and display video controls
+ options = ['controls', 'autoplay']
+
+ # If we're set to repeat, make it loop
+ if getattr(self, '_repeat', False):
+ options.append('loop')
+
+ return VIDEO_TAG.format(video=self._base64_video,
+ size=self._video_size,
+ options=' '.join(options))
+ else:
+ return 'Video too large to embed.'
+
+ def to_jshtml(self, fps=None, embed_frames=True, default_mode=None):
+ """
+ Generate HTML representation of the animation.
+
+ Parameters
+ ----------
+ fps : int, optional
+ Movie frame rate (per second). If not set, the frame rate from
+ the animation's frame interval.
+ embed_frames : bool, optional
+ default_mode : str, optional
+ What to do when the animation ends. Must be one of ``{'loop',
+ 'once', 'reflect'}``. Defaults to ``'loop'`` if the *repeat*
+ parameter is True, otherwise ``'once'``.
+
+ Returns
+ -------
+ str
+ An HTML representation of the animation embedded as a js object as
+ produced with the `.HTMLWriter`.
+ """
+ if fps is None and hasattr(self, '_interval'):
+ # Convert interval in ms to frames per second
+ fps = 1000 / self._interval
+
+ # If we're not given a default mode, choose one base on the value of
+ # the _repeat attribute
+ if default_mode is None:
+ default_mode = 'loop' if getattr(self, '_repeat',
+ False) else 'once'
+
+ if not hasattr(self, "_html_representation"):
+ # Can't open a NamedTemporaryFile twice on Windows, so use a
+ # TemporaryDirectory instead.
+ with TemporaryDirectory() as tmpdir:
+ path = Path(tmpdir, "temp.html")
+ writer = HTMLWriter(fps=fps,
+ embed_frames=embed_frames,
+ default_mode=default_mode)
+ self.save(str(path), writer=writer)
+ self._html_representation = path.read_text()
+
+ return self._html_representation
+
+ def _repr_html_(self):
+ """IPython display hook for rendering."""
+ fmt = mpl.rcParams['animation.html']
+ if fmt == 'html5':
+ return self.to_html5_video()
+ elif fmt == 'jshtml':
+ return self.to_jshtml()
+
+ def pause(self):
+ """Pause the animation."""
+ self.event_source.stop()
+ if self._blit:
+ for artist in self._drawn_artists:
+ artist.set_animated(False)
+
+ def resume(self):
+ """Resume the animation."""
+ self.event_source.start()
+ if self._blit:
+ for artist in self._drawn_artists:
+ artist.set_animated(True)
+
+
+class TimedAnimation(Animation):
+ """
+ `Animation` subclass for time-based animation.
+
+ A new frame is drawn every *interval* milliseconds.
+
+ .. note::
+
+ You must store the created Animation in a variable that lives as long
+ as the animation should run. Otherwise, the Animation object will be
+ garbage-collected and the animation stops.
+
+ Parameters
+ ----------
+ fig : `~matplotlib.figure.Figure`
+ The figure object used to get needed events, such as draw or resize.
+ interval : int, default: 200
+ Delay between frames in milliseconds.
+ repeat_delay : int, default: 0
+ The delay in milliseconds between consecutive animation runs, if
+ *repeat* is True.
+ repeat : bool, default: True
+ Whether the animation repeats when the sequence of frames is completed.
+ blit : bool, default: False
+ Whether blitting is used to optimize drawing.
+ """
+ def __init__(self, fig, interval=200, repeat_delay=0, repeat=True,
+ event_source=None, *args, **kwargs):
+ self._interval = interval
+ # Undocumented support for repeat_delay = None as backcompat.
+ self._repeat_delay = repeat_delay if repeat_delay is not None else 0
+ self._repeat = repeat
+ # If we're not given an event source, create a new timer. This permits
+ # sharing timers between animation objects for syncing animations.
+ if event_source is None:
+ event_source = fig.canvas.new_timer(interval=self._interval)
+ super().__init__(fig, event_source=event_source, *args, **kwargs)
+
+ def _step(self, *args):
+ """Handler for getting events."""
+ # Extends the _step() method for the Animation class. If
+ # Animation._step signals that it reached the end and we want to
+ # repeat, we refresh the frame sequence and return True. If
+ # _repeat_delay is set, change the event_source's interval to our loop
+ # delay and set the callback to one which will then set the interval
+ # back.
+ still_going = super()._step(*args)
+ if not still_going:
+ if self._repeat:
+ # Restart the draw loop
+ self._init_draw()
+ self.frame_seq = self.new_frame_seq()
+ self.event_source.interval = self._repeat_delay
+ return True
+ else:
+ # We are done with the animation. Call pause to remove
+ # animated flags from artists that were using blitting
+ self.pause()
+ if self._blit:
+ # Remove the resize callback if we were blitting
+ self._fig.canvas.mpl_disconnect(self._resize_id)
+ self._fig.canvas.mpl_disconnect(self._close_id)
+ self.event_source = None
+ return False
+
+ self.event_source.interval = self._interval
+ return True
+
+
+class ArtistAnimation(TimedAnimation):
+ """
+ `TimedAnimation` subclass that creates an animation by using a fixed
+ set of `.Artist` objects.
+
+ Before creating an instance, all plotting should have taken place
+ and the relevant artists saved.
+
+ .. note::
+
+ You must store the created Animation in a variable that lives as long
+ as the animation should run. Otherwise, the Animation object will be
+ garbage-collected and the animation stops.
+
+ Parameters
+ ----------
+ fig : `~matplotlib.figure.Figure`
+ The figure object used to get needed events, such as draw or resize.
+ artists : list
+ Each list entry is a collection of `.Artist` objects that are made
+ visible on the corresponding frame. Other artists are made invisible.
+ interval : int, default: 200
+ Delay between frames in milliseconds.
+ repeat_delay : int, default: 0
+ The delay in milliseconds between consecutive animation runs, if
+ *repeat* is True.
+ repeat : bool, default: True
+ Whether the animation repeats when the sequence of frames is completed.
+ blit : bool, default: False
+ Whether blitting is used to optimize drawing.
+ """
+
+ def __init__(self, fig, artists, *args, **kwargs):
+ # Internal list of artists drawn in the most recent frame.
+ self._drawn_artists = []
+
+ # Use the list of artists as the framedata, which will be iterated
+ # over by the machinery.
+ self._framedata = artists
+ super().__init__(fig, *args, **kwargs)
+
+ def _init_draw(self):
+ super()._init_draw()
+ # Make all the artists involved in *any* frame invisible
+ figs = set()
+ for f in self.new_frame_seq():
+ for artist in f:
+ artist.set_visible(False)
+ artist.set_animated(self._blit)
+ # Assemble a list of unique figures that need flushing
+ if artist.get_figure() not in figs:
+ figs.add(artist.get_figure())
+
+ # Flush the needed figures
+ for fig in figs:
+ fig.canvas.draw_idle()
+
+ def _pre_draw(self, framedata, blit):
+ """Clears artists from the last frame."""
+ if blit:
+ # Let blit handle clearing
+ self._blit_clear(self._drawn_artists)
+ else:
+ # Otherwise, make all the artists from the previous frame invisible
+ for artist in self._drawn_artists:
+ artist.set_visible(False)
+
+ def _draw_frame(self, artists):
+ # Save the artists that were passed in as framedata for the other
+ # steps (esp. blitting) to use.
+ self._drawn_artists = artists
+
+ # Make all the artists from the current frame visible
+ for artist in artists:
+ artist.set_visible(True)
+
+
+class FuncAnimation(TimedAnimation):
+ """
+ `TimedAnimation` subclass that makes an animation by repeatedly calling
+ a function *func*.
+
+ .. note::
+
+ You must store the created Animation in a variable that lives as long
+ as the animation should run. Otherwise, the Animation object will be
+ garbage-collected and the animation stops.
+
+ Parameters
+ ----------
+ fig : `~matplotlib.figure.Figure`
+ The figure object used to get needed events, such as draw or resize.
+
+ func : callable
+ The function to call at each frame. The first argument will
+ be the next value in *frames*. Any additional positional
+ arguments can be supplied using `functools.partial` or via the *fargs*
+ parameter.
+
+ The required signature is::
+
+ def func(frame, *fargs) -> iterable_of_artists
+
+ It is often more convenient to provide the arguments using
+ `functools.partial`. In this way it is also possible to pass keyword
+ arguments. To pass a function with both positional and keyword
+ arguments, set all arguments as keyword arguments, just leaving the
+ *frame* argument unset::
+
+ def func(frame, art, *, y=None):
+ ...
+
+ ani = FuncAnimation(fig, partial(func, art=ln, y='foo'))
+
+ If ``blit == True``, *func* must return an iterable of all artists
+ that were modified or created. This information is used by the blitting
+ algorithm to determine which parts of the figure have to be updated.
+ The return value is unused if ``blit == False`` and may be omitted in
+ that case.
+
+ frames : iterable, int, generator function, or None, optional
+ Source of data to pass *func* and each frame of the animation
+
+ - If an iterable, then simply use the values provided. If the
+ iterable has a length, it will override the *save_count* kwarg.
+
+ - If an integer, then equivalent to passing ``range(frames)``
+
+ - If a generator function, then must have the signature::
+
+ def gen_function() -> obj
+
+ - If *None*, then equivalent to passing ``itertools.count``.
+
+ In all of these cases, the values in *frames* is simply passed through
+ to the user-supplied *func* and thus can be of any type.
+
+ init_func : callable, optional
+ A function used to draw a clear frame. If not given, the results of
+ drawing from the first item in the frames sequence will be used. This
+ function will be called once before the first frame.
+
+ The required signature is::
+
+ def init_func() -> iterable_of_artists
+
+ If ``blit == True``, *init_func* must return an iterable of artists
+ to be re-drawn. This information is used by the blitting algorithm to
+ determine which parts of the figure have to be updated. The return
+ value is unused if ``blit == False`` and may be omitted in that case.
+
+ fargs : tuple or None, optional
+ Additional arguments to pass to each call to *func*. Note: the use of
+ `functools.partial` is preferred over *fargs*. See *func* for details.
+
+ save_count : int, optional
+ Fallback for the number of values from *frames* to cache. This is
+ only used if the number of frames cannot be inferred from *frames*,
+ i.e. when it's an iterator without length or a generator.
+
+ interval : int, default: 200
+ Delay between frames in milliseconds.
+
+ repeat_delay : int, default: 0
+ The delay in milliseconds between consecutive animation runs, if
+ *repeat* is True.
+
+ repeat : bool, default: True
+ Whether the animation repeats when the sequence of frames is completed.
+
+ blit : bool, default: False
+ Whether blitting is used to optimize drawing. Note: when using
+ blitting, any animated artists will be drawn according to their zorder;
+ however, they will be drawn on top of any previous artists, regardless
+ of their zorder.
+
+ cache_frame_data : bool, default: True
+ Whether frame data is cached. Disabling cache might be helpful when
+ frames contain large objects.
+ """
+ def __init__(self, fig, func, frames=None, init_func=None, fargs=None,
+ save_count=None, *, cache_frame_data=True, **kwargs):
+ if fargs:
+ self._args = fargs
+ else:
+ self._args = ()
+ self._func = func
+ self._init_func = init_func
+
+ # Amount of framedata to keep around for saving movies. This is only
+ # used if we don't know how many frames there will be: in the case
+ # of no generator or in the case of a callable.
+ self._save_count = save_count
+ # Set up a function that creates a new iterable when needed. If nothing
+ # is passed in for frames, just use itertools.count, which will just
+ # keep counting from 0. A callable passed in for frames is assumed to
+ # be a generator. An iterable will be used as is, and anything else
+ # will be treated as a number of frames.
+ if frames is None:
+ self._iter_gen = itertools.count
+ elif callable(frames):
+ self._iter_gen = frames
+ elif np.iterable(frames):
+ if kwargs.get('repeat', True):
+ self._tee_from = frames
+ def iter_frames(frames=frames):
+ this, self._tee_from = itertools.tee(self._tee_from, 2)
+ yield from this
+ self._iter_gen = iter_frames
+ else:
+ self._iter_gen = lambda: iter(frames)
+ if hasattr(frames, '__len__'):
+ self._save_count = len(frames)
+ if save_count is not None:
+ _api.warn_external(
+ f"You passed in an explicit {save_count=} "
+ "which is being ignored in favor of "
+ f"{len(frames)=}."
+ )
+ else:
+ self._iter_gen = lambda: iter(range(frames))
+ self._save_count = frames
+ if save_count is not None:
+ _api.warn_external(
+ f"You passed in an explicit {save_count=} which is being "
+ f"ignored in favor of {frames=}."
+ )
+ if self._save_count is None and cache_frame_data:
+ _api.warn_external(
+ f"{frames=!r} which we can infer the length of, "
+ "did not pass an explicit *save_count* "
+ f"and passed {cache_frame_data=}. To avoid a possibly "
+ "unbounded cache, frame data caching has been disabled. "
+ "To suppress this warning either pass "
+ "`cache_frame_data=False` or `save_count=MAX_FRAMES`."
+ )
+ cache_frame_data = False
+
+ self._cache_frame_data = cache_frame_data
+
+ # Needs to be initialized so the draw functions work without checking
+ self._save_seq = []
+
+ super().__init__(fig, **kwargs)
+
+ # Need to reset the saved seq, since right now it will contain data
+ # for a single frame from init, which is not what we want.
+ self._save_seq = []
+
+ def new_frame_seq(self):
+ # Use the generating function to generate a new frame sequence
+ return self._iter_gen()
+
+ def new_saved_frame_seq(self):
+ # Generate an iterator for the sequence of saved data. If there are
+ # no saved frames, generate a new frame sequence and take the first
+ # save_count entries in it.
+ if self._save_seq:
+ # While iterating we are going to update _save_seq
+ # so make a copy to safely iterate over
+ self._old_saved_seq = list(self._save_seq)
+ return iter(self._old_saved_seq)
+ else:
+ if self._save_count is None:
+ frame_seq = self.new_frame_seq()
+
+ def gen():
+ try:
+ while True:
+ yield next(frame_seq)
+ except StopIteration:
+ pass
+ return gen()
+ else:
+ return itertools.islice(self.new_frame_seq(), self._save_count)
+
+ def _init_draw(self):
+ super()._init_draw()
+ # Initialize the drawing either using the given init_func or by
+ # calling the draw function with the first item of the frame sequence.
+ # For blitting, the init_func should return a sequence of modified
+ # artists.
+ if self._init_func is None:
+ try:
+ frame_data = next(self.new_frame_seq())
+ except StopIteration:
+ # we can't start the iteration, it may have already been
+ # exhausted by a previous save or just be 0 length.
+ # warn and bail.
+ warnings.warn(
+ "Can not start iterating the frames for the initial draw. "
+ "This can be caused by passing in a 0 length sequence "
+ "for *frames*.\n\n"
+ "If you passed *frames* as a generator "
+ "it may be exhausted due to a previous display or save."
+ )
+ return
+ self._draw_frame(frame_data)
+ else:
+ self._drawn_artists = self._init_func()
+ if self._blit:
+ if self._drawn_artists is None:
+ raise RuntimeError('The init_func must return a '
+ 'sequence of Artist objects.')
+ for a in self._drawn_artists:
+ a.set_animated(self._blit)
+ self._save_seq = []
+
+ def _draw_frame(self, framedata):
+ if self._cache_frame_data:
+ # Save the data for potential saving of movies.
+ self._save_seq.append(framedata)
+ self._save_seq = self._save_seq[-self._save_count:]
+
+ # Call the func with framedata and args. If blitting is desired,
+ # func needs to return a sequence of any artists that were modified.
+ self._drawn_artists = self._func(framedata, *self._args)
+
+ if self._blit:
+
+ err = RuntimeError('The animation function must return a sequence '
+ 'of Artist objects.')
+ try:
+ # check if a sequence
+ iter(self._drawn_artists)
+ except TypeError:
+ raise err from None
+
+ # check each item if it's artist
+ for i in self._drawn_artists:
+ if not isinstance(i, mpl.artist.Artist):
+ raise err
+
+ self._drawn_artists = sorted(self._drawn_artists,
+ key=lambda x: x.get_zorder())
+
+ for a in self._drawn_artists:
+ a.set_animated(self._blit)
+
+
+def _validate_grabframe_kwargs(savefig_kwargs):
+ if mpl.rcParams['savefig.bbox'] == 'tight':
+ raise ValueError(
+ f"{mpl.rcParams['savefig.bbox']=} must not be 'tight' as it "
+ "may cause frame size to vary, which is inappropriate for animation."
+ )
+ for k in ('dpi', 'bbox_inches', 'format'):
+ if k in savefig_kwargs:
+ raise TypeError(
+ f"grab_frame got an unexpected keyword argument {k!r}"
+ )
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/animation.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/animation.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..345e3c6dbe61f1b3c99eba4c9e77edb0c51cff3e
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/animation.pyi
@@ -0,0 +1,217 @@
+import abc
+from collections.abc import Callable, Collection, Iterable, Sequence, Generator
+import contextlib
+from pathlib import Path
+from matplotlib.artist import Artist
+from matplotlib.backend_bases import TimerBase
+from matplotlib.figure import Figure
+
+from typing import Any
+
+subprocess_creation_flags: int
+
+def adjusted_figsize(w: float, h: float, dpi: float, n: int) -> tuple[float, float]: ...
+
+class MovieWriterRegistry:
+ def __init__(self) -> None: ...
+ def register(
+ self, name: str
+ ) -> Callable[[type[AbstractMovieWriter]], type[AbstractMovieWriter]]: ...
+ def is_available(self, name: str) -> bool: ...
+ def __iter__(self) -> Generator[str, None, None]: ...
+ def list(self) -> list[str]: ...
+ def __getitem__(self, name: str) -> type[AbstractMovieWriter]: ...
+
+writers: MovieWriterRegistry
+
+class AbstractMovieWriter(abc.ABC, metaclass=abc.ABCMeta):
+ fps: int
+ metadata: dict[str, str]
+ codec: str
+ bitrate: int
+ def __init__(
+ self,
+ fps: int = ...,
+ metadata: dict[str, str] | None = ...,
+ codec: str | None = ...,
+ bitrate: int | None = ...,
+ ) -> None: ...
+ outfile: str | Path
+ fig: Figure
+ dpi: float
+
+ @abc.abstractmethod
+ def setup(self, fig: Figure, outfile: str | Path, dpi: float | None = ...) -> None: ...
+ @property
+ def frame_size(self) -> tuple[int, int]: ...
+ @abc.abstractmethod
+ def grab_frame(self, **savefig_kwargs) -> None: ...
+ @abc.abstractmethod
+ def finish(self) -> None: ...
+ @contextlib.contextmanager
+ def saving(
+ self, fig: Figure, outfile: str | Path, dpi: float | None, *args, **kwargs
+ ) -> Generator[AbstractMovieWriter, None, None]: ...
+
+class MovieWriter(AbstractMovieWriter):
+ supported_formats: list[str]
+ frame_format: str
+ extra_args: list[str] | None
+ def __init__(
+ self,
+ fps: int = ...,
+ codec: str | None = ...,
+ bitrate: int | None = ...,
+ extra_args: list[str] | None = ...,
+ metadata: dict[str, str] | None = ...,
+ ) -> None: ...
+ def setup(self, fig: Figure, outfile: str | Path, dpi: float | None = ...) -> None: ...
+ def grab_frame(self, **savefig_kwargs) -> None: ...
+ def finish(self) -> None: ...
+ @classmethod
+ def bin_path(cls) -> str: ...
+ @classmethod
+ def isAvailable(cls) -> bool: ...
+
+class FileMovieWriter(MovieWriter):
+ fig: Figure
+ outfile: str | Path
+ dpi: float
+ temp_prefix: str
+ fname_format_str: str
+ def setup(
+ self,
+ fig: Figure,
+ outfile: str | Path,
+ dpi: float | None = ...,
+ frame_prefix: str | Path | None = ...,
+ ) -> None: ...
+ def __del__(self) -> None: ...
+ @property
+ def frame_format(self) -> str: ...
+ @frame_format.setter
+ def frame_format(self, frame_format: str) -> None: ...
+
+class PillowWriter(AbstractMovieWriter):
+ @classmethod
+ def isAvailable(cls) -> bool: ...
+ def setup(
+ self, fig: Figure, outfile: str | Path, dpi: float | None = ...
+ ) -> None: ...
+ def grab_frame(self, **savefig_kwargs) -> None: ...
+ def finish(self) -> None: ...
+
+class FFMpegBase:
+ codec: str
+ @property
+ def output_args(self) -> list[str]: ...
+
+class FFMpegWriter(FFMpegBase, MovieWriter): ...
+
+class FFMpegFileWriter(FFMpegBase, FileMovieWriter):
+ supported_formats: list[str]
+
+class ImageMagickBase:
+ @classmethod
+ def bin_path(cls) -> str: ...
+ @classmethod
+ def isAvailable(cls) -> bool: ...
+
+class ImageMagickWriter(ImageMagickBase, MovieWriter):
+ input_names: str
+
+class ImageMagickFileWriter(ImageMagickBase, FileMovieWriter):
+ supported_formats: list[str]
+ @property
+ def input_names(self) -> str: ...
+
+class HTMLWriter(FileMovieWriter):
+ supported_formats: list[str]
+ @classmethod
+ def isAvailable(cls) -> bool: ...
+ embed_frames: bool
+ default_mode: str
+ def __init__(
+ self,
+ fps: int = ...,
+ codec: str | None = ...,
+ bitrate: int | None = ...,
+ extra_args: list[str] | None = ...,
+ metadata: dict[str, str] | None = ...,
+ embed_frames: bool = ...,
+ default_mode: str = ...,
+ embed_limit: float | None = ...,
+ ) -> None: ...
+ def setup(
+ self,
+ fig: Figure,
+ outfile: str | Path,
+ dpi: float | None = ...,
+ frame_dir: str | Path | None = ...,
+ ) -> None: ...
+ def grab_frame(self, **savefig_kwargs): ...
+ def finish(self) -> None: ...
+
+class Animation:
+ frame_seq: Iterable[Artist]
+ event_source: Any
+ def __init__(
+ self, fig: Figure, event_source: Any | None = ..., blit: bool = ...
+ ) -> None: ...
+ def __del__(self) -> None: ...
+ def save(
+ self,
+ filename: str | Path,
+ writer: AbstractMovieWriter | str | None = ...,
+ fps: int | None = ...,
+ dpi: float | None = ...,
+ codec: str | None = ...,
+ bitrate: int | None = ...,
+ extra_args: list[str] | None = ...,
+ metadata: dict[str, str] | None = ...,
+ extra_anim: list[Animation] | None = ...,
+ savefig_kwargs: dict[str, Any] | None = ...,
+ *,
+ progress_callback: Callable[[int, int], Any] | None = ...
+ ) -> None: ...
+ def new_frame_seq(self) -> Iterable[Artist]: ...
+ def new_saved_frame_seq(self) -> Iterable[Artist]: ...
+ def to_html5_video(self, embed_limit: float | None = ...) -> str: ...
+ def to_jshtml(
+ self,
+ fps: int | None = ...,
+ embed_frames: bool = ...,
+ default_mode: str | None = ...,
+ ) -> str: ...
+ def _repr_html_(self) -> str: ...
+ def pause(self) -> None: ...
+ def resume(self) -> None: ...
+
+class TimedAnimation(Animation):
+ def __init__(
+ self,
+ fig: Figure,
+ interval: int = ...,
+ repeat_delay: int = ...,
+ repeat: bool = ...,
+ event_source: TimerBase | None = ...,
+ *args,
+ **kwargs
+ ) -> None: ...
+
+class ArtistAnimation(TimedAnimation):
+ def __init__(self, fig: Figure, artists: Sequence[Collection[Artist]], *args, **kwargs) -> None: ...
+
+class FuncAnimation(TimedAnimation):
+ def __init__(
+ self,
+ fig: Figure,
+ func: Callable[..., Iterable[Artist]],
+ frames: Iterable | int | Callable[[], Generator] | None = ...,
+ init_func: Callable[[], Iterable[Artist]] | None = ...,
+ fargs: tuple[Any, ...] | None = ...,
+ save_count: int | None = ...,
+ *,
+ cache_frame_data: bool = ...,
+ **kwargs
+ ) -> None: ...
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/artist.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/artist.py
new file mode 100644
index 0000000000000000000000000000000000000000..c87c789048c4982e1b25507fe3c360e003a0def6
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/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/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/artist.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/artist.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..be23f69d44a6df19fef57131eadede93bf4875bc
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/artist.pyi
@@ -0,0 +1,199 @@
+from .axes._base import _AxesBase
+from .backend_bases import RendererBase, MouseEvent
+from .figure import Figure, SubFigure
+from .path import Path
+from .patches import Patch
+from .patheffects import AbstractPathEffect
+from .transforms import (
+ BboxBase,
+ Bbox,
+ Transform,
+ TransformedPatchPath,
+ TransformedPath,
+)
+
+import numpy as np
+
+from collections.abc import Callable, Iterable
+from typing import Any, Literal, NamedTuple, TextIO, overload, TypeVar
+from numpy.typing import ArrayLike
+
+_T_Artist = TypeVar("_T_Artist", bound=Artist)
+
+def allow_rasterization(draw): ...
+
+class _XYPair(NamedTuple):
+ x: ArrayLike
+ y: ArrayLike
+
+class _Unset: ...
+
+class Artist:
+ zorder: float
+ stale_callback: Callable[[Artist, bool], None] | None
+ @property
+ def figure(self) -> Figure | SubFigure: ...
+ clipbox: BboxBase | None
+ def __init__(self) -> None: ...
+ def remove(self) -> None: ...
+ def have_units(self) -> bool: ...
+ # TODO units
+ def convert_xunits(self, x): ...
+ def convert_yunits(self, y): ...
+ @property
+ def axes(self) -> _AxesBase | None: ...
+ @axes.setter
+ def axes(self, new_axes: _AxesBase | None) -> None: ...
+ @property
+ def stale(self) -> bool: ...
+ @stale.setter
+ def stale(self, val: bool) -> None: ...
+ def get_window_extent(self, renderer: RendererBase | None = ...) -> Bbox: ...
+ def get_tightbbox(self, renderer: RendererBase | None = ...) -> Bbox | None: ...
+ def add_callback(self, func: Callable[[Artist], Any]) -> int: ...
+ def remove_callback(self, oid: int) -> None: ...
+ def pchanged(self) -> None: ...
+ def is_transform_set(self) -> bool: ...
+ def set_transform(self, t: Transform | None) -> None: ...
+ def get_transform(self) -> Transform: ...
+ def get_children(self) -> list[Artist]: ...
+ # TODO can these dicts be type narrowed? e.g. str keys
+ def contains(self, mouseevent: MouseEvent) -> tuple[bool, dict[Any, Any]]: ...
+ def pickable(self) -> bool: ...
+ def pick(self, mouseevent: MouseEvent) -> None: ...
+ def set_picker(
+ self,
+ picker: None
+ | bool
+ | float
+ | Callable[[Artist, MouseEvent], tuple[bool, dict[Any, Any]]],
+ ) -> None: ...
+ def get_picker(
+ self,
+ ) -> None | bool | float | Callable[
+ [Artist, MouseEvent], tuple[bool, dict[Any, Any]]
+ ]: ...
+ def get_url(self) -> str | None: ...
+ def set_url(self, url: str | None) -> None: ...
+ def get_gid(self) -> str | None: ...
+ def set_gid(self, gid: str | None) -> None: ...
+ def get_snap(self) -> bool | None: ...
+ def set_snap(self, snap: bool | None) -> 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: ...
+ def set_path_effects(self, path_effects: list[AbstractPathEffect]) -> None: ...
+ def get_path_effects(self) -> list[AbstractPathEffect]: ...
+ @overload
+ def get_figure(self, root: Literal[True]) -> Figure | None: ...
+ @overload
+ def get_figure(self, root: Literal[False]) -> Figure | SubFigure | None: ...
+ @overload
+ def get_figure(self, root: bool = ...) -> Figure | SubFigure | None: ...
+ def set_figure(self, fig: Figure | SubFigure) -> None: ...
+ def set_clip_box(self, clipbox: BboxBase | None) -> None: ...
+ def set_clip_path(
+ self,
+ path: Patch | Path | TransformedPath | TransformedPatchPath | None,
+ transform: Transform | None = ...,
+ ) -> None: ...
+ def get_alpha(self) -> float | None: ...
+ def get_visible(self) -> bool: ...
+ def get_animated(self) -> bool: ...
+ def get_in_layout(self) -> bool: ...
+ def get_clip_on(self) -> bool: ...
+ def get_clip_box(self) -> Bbox | None: ...
+ def get_clip_path(
+ self,
+ ) -> Patch | Path | TransformedPath | TransformedPatchPath | None: ...
+ def get_transformed_clip_path_and_affine(
+ self,
+ ) -> tuple[None, None] | tuple[Path, Transform]: ...
+ def set_clip_on(self, b: bool) -> None: ...
+ def get_rasterized(self) -> bool: ...
+ def set_rasterized(self, rasterized: bool) -> None: ...
+ def get_agg_filter(self) -> Callable[[ArrayLike, float], tuple[np.ndarray, float, float]] | None: ...
+ def set_agg_filter(
+ self, filter_func: Callable[[ArrayLike, float], tuple[np.ndarray, float, float]] | None
+ ) -> None: ...
+ def draw(self, renderer: RendererBase) -> None: ...
+ def set_alpha(self, alpha: float | None) -> None: ...
+ def set_visible(self, b: bool) -> None: ...
+ def set_animated(self, b: bool) -> None: ...
+ def set_in_layout(self, in_layout: bool) -> None: ...
+ def get_label(self) -> object: ...
+ def set_label(self, s: object) -> None: ...
+ def get_zorder(self) -> float: ...
+ def set_zorder(self, level: float) -> None: ...
+ @property
+ def sticky_edges(self) -> _XYPair: ...
+ def update_from(self, other: Artist) -> None: ...
+ def properties(self) -> dict[str, Any]: ...
+ def update(self, props: dict[str, Any]) -> list[Any]: ...
+ def _internal_update(self, kwargs: Any) -> list[Any]: ...
+ def set(self, **kwargs: Any) -> list[Any]: ...
+
+ @overload
+ def findobj(
+ self,
+ match: None | Callable[[Artist], bool] = ...,
+ include_self: bool = ...,
+ ) -> list[Artist]: ...
+
+ @overload
+ def findobj(
+ self,
+ match: type[_T_Artist],
+ include_self: bool = ...,
+ ) -> list[_T_Artist]: ...
+
+ def get_cursor_data(self, event: MouseEvent) -> Any: ...
+ def format_cursor_data(self, data: Any) -> str: ...
+ def get_mouseover(self) -> bool: ...
+ def set_mouseover(self, mouseover: bool) -> None: ...
+ @property
+ def mouseover(self) -> bool: ...
+ @mouseover.setter
+ def mouseover(self, mouseover: bool) -> None: ...
+
+class ArtistInspector:
+ oorig: Artist | type[Artist]
+ o: type[Artist]
+ aliasd: dict[str, set[str]]
+ def __init__(
+ self, o: Artist | type[Artist] | Iterable[Artist | type[Artist]]
+ ) -> None: ...
+ def get_aliases(self) -> dict[str, set[str]]: ...
+ def get_valid_values(self, attr: str) -> str | None: ...
+ def get_setters(self) -> list[str]: ...
+ @staticmethod
+ def number_of_parameters(func: Callable) -> int: ...
+ @staticmethod
+ def is_alias(method: Callable) -> bool: ...
+ def aliased_name(self, s: str) -> str: ...
+ def aliased_name_rest(self, s: str, target: str) -> str: ...
+ @overload
+ def pprint_setters(
+ self, prop: None = ..., leadingspace: int = ...
+ ) -> list[str]: ...
+ @overload
+ def pprint_setters(self, prop: str, leadingspace: int = ...) -> str: ...
+ @overload
+ def pprint_setters_rest(
+ self, prop: None = ..., leadingspace: int = ...
+ ) -> list[str]: ...
+ @overload
+ def pprint_setters_rest(self, prop: str, leadingspace: int = ...) -> str: ...
+ def properties(self) -> dict[str, Any]: ...
+ def pprint_getters(self) -> list[str]: ...
+
+def getp(obj: Artist, property: str | None = ...) -> Any: ...
+
+get = getp
+
+def setp(obj: Artist, *args, file: TextIO | None = ..., **kwargs) -> list[Any] | None: ...
+def kwdoc(artist: Artist | type[Artist] | Iterable[Artist | type[Artist]]) -> str: ...
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/axis.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/axis.py
new file mode 100644
index 0000000000000000000000000000000000000000..714fb08f55be9a2a7967073960031785b50e0df1
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/axis.py
@@ -0,0 +1,2819 @@
+"""
+Classes for the ticks and x- and y-axis.
+"""
+
+import datetime
+import functools
+import logging
+from numbers import Real
+import warnings
+
+import numpy as np
+
+import matplotlib as mpl
+from matplotlib import _api, cbook
+import matplotlib.artist as martist
+import matplotlib.colors as mcolors
+import matplotlib.lines as mlines
+import matplotlib.scale as mscale
+import matplotlib.text as mtext
+import matplotlib.ticker as mticker
+import matplotlib.transforms as mtransforms
+import matplotlib.units as munits
+
+_log = logging.getLogger(__name__)
+
+GRIDLINE_INTERPOLATION_STEPS = 180
+
+# This list is being used for compatibility with Axes.grid, which
+# allows all Line2D kwargs.
+_line_inspector = martist.ArtistInspector(mlines.Line2D)
+_line_param_names = _line_inspector.get_setters()
+_line_param_aliases = [next(iter(d)) for d in _line_inspector.aliasd.values()]
+_gridline_param_names = ['grid_' + name
+ for name in _line_param_names + _line_param_aliases]
+
+
+class Tick(martist.Artist):
+ """
+ Abstract base class for the axis ticks, grid lines and labels.
+
+ Ticks mark a position on an Axis. They contain two lines as markers and
+ two labels; one each for the bottom and top positions (in case of an
+ `.XAxis`) or for the left and right positions (in case of a `.YAxis`).
+
+ Attributes
+ ----------
+ tick1line : `~matplotlib.lines.Line2D`
+ The left/bottom tick marker.
+ tick2line : `~matplotlib.lines.Line2D`
+ The right/top tick marker.
+ gridline : `~matplotlib.lines.Line2D`
+ The grid line associated with the label position.
+ label1 : `~matplotlib.text.Text`
+ The left/bottom tick label.
+ label2 : `~matplotlib.text.Text`
+ The right/top tick label.
+
+ """
+ def __init__(
+ self, axes, loc, *,
+ size=None, # points
+ width=None,
+ color=None,
+ tickdir=None,
+ pad=None,
+ labelsize=None,
+ labelcolor=None,
+ labelfontfamily=None,
+ zorder=None,
+ gridOn=None, # defaults to axes.grid depending on axes.grid.which
+ tick1On=True,
+ tick2On=True,
+ label1On=True,
+ label2On=False,
+ major=True,
+ labelrotation=0,
+ grid_color=None,
+ grid_linestyle=None,
+ grid_linewidth=None,
+ grid_alpha=None,
+ **kwargs, # Other Line2D kwargs applied to gridlines.
+ ):
+ """
+ bbox is the Bound2D bounding box in display coords of the Axes
+ loc is the tick location in data coords
+ size is the tick size in points
+ """
+ super().__init__()
+
+ if gridOn is None:
+ which = mpl.rcParams['axes.grid.which']
+ if major and (which in ('both', 'major')):
+ gridOn = mpl.rcParams['axes.grid']
+ elif (not major) and (which in ('both', 'minor')):
+ gridOn = mpl.rcParams['axes.grid']
+ else:
+ gridOn = False
+
+ self.set_figure(axes.get_figure(root=False))
+ self.axes = axes
+
+ self._loc = loc
+ self._major = major
+
+ name = self.__name__
+ major_minor = "major" if major else "minor"
+
+ if size is None:
+ size = mpl.rcParams[f"{name}.{major_minor}.size"]
+ self._size = size
+
+ if width is None:
+ width = mpl.rcParams[f"{name}.{major_minor}.width"]
+ self._width = width
+
+ if color is None:
+ color = mpl.rcParams[f"{name}.color"]
+
+ if pad is None:
+ pad = mpl.rcParams[f"{name}.{major_minor}.pad"]
+ self._base_pad = pad
+
+ if labelcolor is None:
+ labelcolor = mpl.rcParams[f"{name}.labelcolor"]
+
+ if cbook._str_equal(labelcolor, 'inherit'):
+ # inherit from tick color
+ labelcolor = mpl.rcParams[f"{name}.color"]
+
+ if labelsize is None:
+ labelsize = mpl.rcParams[f"{name}.labelsize"]
+
+ self._set_labelrotation(labelrotation)
+
+ if zorder is None:
+ if major:
+ zorder = mlines.Line2D.zorder + 0.01
+ else:
+ zorder = mlines.Line2D.zorder
+ self._zorder = zorder
+
+ grid_color = mpl._val_or_rc(grid_color, "grid.color")
+ grid_linestyle = mpl._val_or_rc(grid_linestyle, "grid.linestyle")
+ grid_linewidth = mpl._val_or_rc(grid_linewidth, "grid.linewidth")
+ if grid_alpha is None and not mcolors._has_alpha_channel(grid_color):
+ # alpha precedence: kwarg > color alpha > rcParams['grid.alpha']
+ # Note: only resolve to rcParams if the color does not have alpha
+ # otherwise `grid(color=(1, 1, 1, 0.5))` would work like
+ # grid(color=(1, 1, 1, 0.5), alpha=rcParams['grid.alpha'])
+ # so the that the rcParams default would override color alpha.
+ grid_alpha = mpl.rcParams["grid.alpha"]
+ grid_kw = {k[5:]: v for k, v in kwargs.items()}
+
+ self.tick1line = mlines.Line2D(
+ [], [],
+ color=color, linestyle="none", zorder=zorder, visible=tick1On,
+ markeredgecolor=color, markersize=size, markeredgewidth=width,
+ )
+ self.tick2line = mlines.Line2D(
+ [], [],
+ color=color, linestyle="none", zorder=zorder, visible=tick2On,
+ markeredgecolor=color, markersize=size, markeredgewidth=width,
+ )
+ self.gridline = mlines.Line2D(
+ [], [],
+ color=grid_color, alpha=grid_alpha, visible=gridOn,
+ linestyle=grid_linestyle, linewidth=grid_linewidth, marker="",
+ **grid_kw,
+ )
+ self.gridline.get_path()._interpolation_steps = \
+ GRIDLINE_INTERPOLATION_STEPS
+ self.label1 = mtext.Text(
+ np.nan, np.nan,
+ fontsize=labelsize, color=labelcolor, visible=label1On,
+ fontfamily=labelfontfamily, rotation=self._labelrotation[1])
+ self.label2 = mtext.Text(
+ np.nan, np.nan,
+ fontsize=labelsize, color=labelcolor, visible=label2On,
+ fontfamily=labelfontfamily, rotation=self._labelrotation[1])
+
+ self._apply_tickdir(tickdir)
+
+ for artist in [self.tick1line, self.tick2line, self.gridline,
+ self.label1, self.label2]:
+ self._set_artist_props(artist)
+
+ self.update_position(loc)
+
+ def _set_labelrotation(self, labelrotation):
+ if isinstance(labelrotation, str):
+ mode = labelrotation
+ angle = 0
+ elif isinstance(labelrotation, (tuple, list)):
+ mode, angle = labelrotation
+ else:
+ mode = 'default'
+ angle = labelrotation
+ _api.check_in_list(['auto', 'default'], labelrotation=mode)
+ self._labelrotation = (mode, angle)
+
+ @property
+ def _pad(self):
+ return self._base_pad + self.get_tick_padding()
+
+ def _apply_tickdir(self, tickdir):
+ """Set tick direction. Valid values are 'out', 'in', 'inout'."""
+ # This method is responsible for verifying input and, in subclasses, for setting
+ # the tick{1,2}line markers. From the user perspective this should always be
+ # called through _apply_params, which further updates ticklabel positions using
+ # the new pads.
+ if tickdir is None:
+ tickdir = mpl.rcParams[f'{self.__name__}.direction']
+ else:
+ _api.check_in_list(['in', 'out', 'inout'], tickdir=tickdir)
+ self._tickdir = tickdir
+
+ def get_tickdir(self):
+ return self._tickdir
+
+ def get_tick_padding(self):
+ """Get the length of the tick outside of the Axes."""
+ padding = {
+ 'in': 0.0,
+ 'inout': 0.5,
+ 'out': 1.0
+ }
+ return self._size * padding[self._tickdir]
+
+ def get_children(self):
+ children = [self.tick1line, self.tick2line,
+ self.gridline, self.label1, self.label2]
+ return children
+
+ def set_clip_path(self, path, transform=None):
+ # docstring inherited
+ super().set_clip_path(path, transform)
+ self.gridline.set_clip_path(path, transform)
+ self.stale = True
+
+ def contains(self, mouseevent):
+ """
+ Test whether the mouse event occurred in the Tick marks.
+
+ This function always returns false. It is more useful to test if the
+ axis as a whole contains the mouse rather than the set of tick marks.
+ """
+ return False, {}
+
+ def set_pad(self, val):
+ """
+ Set the tick label pad in points
+
+ Parameters
+ ----------
+ val : float
+ """
+ self._apply_params(pad=val)
+ self.stale = True
+
+ def get_pad(self):
+ """Get the value of the tick label pad in points."""
+ return self._base_pad
+
+ def get_loc(self):
+ """Return the tick location (data coords) as a scalar."""
+ return self._loc
+
+ @martist.allow_rasterization
+ def draw(self, renderer):
+ if not self.get_visible():
+ self.stale = False
+ return
+ renderer.open_group(self.__name__, gid=self.get_gid())
+ for artist in [self.gridline, self.tick1line, self.tick2line,
+ self.label1, self.label2]:
+ artist.draw(renderer)
+ renderer.close_group(self.__name__)
+ self.stale = False
+
+ def set_url(self, url):
+ """
+ Set the url of label1 and label2.
+
+ Parameters
+ ----------
+ url : str
+ """
+ super().set_url(url)
+ self.label1.set_url(url)
+ self.label2.set_url(url)
+ self.stale = True
+
+ def _set_artist_props(self, a):
+ a.set_figure(self.get_figure(root=False))
+
+ def get_view_interval(self):
+ """
+ Return the view limits ``(min, max)`` of the axis the tick belongs to.
+ """
+ raise NotImplementedError('Derived must override')
+
+ def _apply_params(self, **kwargs):
+ for name, target in [("gridOn", self.gridline),
+ ("tick1On", self.tick1line),
+ ("tick2On", self.tick2line),
+ ("label1On", self.label1),
+ ("label2On", self.label2)]:
+ if name in kwargs:
+ target.set_visible(kwargs.pop(name))
+ if any(k in kwargs for k in ['size', 'width', 'pad', 'tickdir']):
+ self._size = kwargs.pop('size', self._size)
+ # Width could be handled outside this block, but it is
+ # convenient to leave it here.
+ self._width = kwargs.pop('width', self._width)
+ self._base_pad = kwargs.pop('pad', self._base_pad)
+ # _apply_tickdir uses _size and _base_pad to make _pad, and also
+ # sets the ticklines markers.
+ self._apply_tickdir(kwargs.pop('tickdir', self._tickdir))
+ for line in (self.tick1line, self.tick2line):
+ line.set_markersize(self._size)
+ line.set_markeredgewidth(self._width)
+ # _get_text1_transform uses _pad from _apply_tickdir.
+ trans = self._get_text1_transform()[0]
+ self.label1.set_transform(trans)
+ trans = self._get_text2_transform()[0]
+ self.label2.set_transform(trans)
+ tick_kw = {k: v for k, v in kwargs.items() if k in ['color', 'zorder']}
+ if 'color' in kwargs:
+ tick_kw['markeredgecolor'] = kwargs['color']
+ self.tick1line.set(**tick_kw)
+ self.tick2line.set(**tick_kw)
+ for k, v in tick_kw.items():
+ setattr(self, '_' + k, v)
+
+ if 'labelrotation' in kwargs:
+ self._set_labelrotation(kwargs.pop('labelrotation'))
+ self.label1.set(rotation=self._labelrotation[1])
+ self.label2.set(rotation=self._labelrotation[1])
+
+ label_kw = {k[5:]: v for k, v in kwargs.items()
+ if k in ['labelsize', 'labelcolor', 'labelfontfamily']}
+ self.label1.set(**label_kw)
+ self.label2.set(**label_kw)
+
+ grid_kw = {k[5:]: v for k, v in kwargs.items()
+ if k in _gridline_param_names}
+ self.gridline.set(**grid_kw)
+
+ def update_position(self, loc):
+ """Set the location of tick in data coords with scalar *loc*."""
+ raise NotImplementedError('Derived must override')
+
+ def _get_text1_transform(self):
+ raise NotImplementedError('Derived must override')
+
+ def _get_text2_transform(self):
+ raise NotImplementedError('Derived must override')
+
+
+class XTick(Tick):
+ """
+ Contains all the Artists needed to make an x tick - the tick line,
+ the label text and the grid line
+ """
+ __name__ = 'xtick'
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ # x in data coords, y in axes coords
+ ax = self.axes
+ self.tick1line.set(
+ data=([0], [0]), transform=ax.get_xaxis_transform("tick1"))
+ self.tick2line.set(
+ data=([0], [1]), transform=ax.get_xaxis_transform("tick2"))
+ self.gridline.set(
+ data=([0, 0], [0, 1]), transform=ax.get_xaxis_transform("grid"))
+ # the y loc is 3 points below the min of y axis
+ trans, va, ha = self._get_text1_transform()
+ self.label1.set(
+ x=0, y=0,
+ verticalalignment=va, horizontalalignment=ha, transform=trans,
+ )
+ trans, va, ha = self._get_text2_transform()
+ self.label2.set(
+ x=0, y=1,
+ verticalalignment=va, horizontalalignment=ha, transform=trans,
+ )
+
+ def _get_text1_transform(self):
+ return self.axes.get_xaxis_text1_transform(self._pad)
+
+ def _get_text2_transform(self):
+ return self.axes.get_xaxis_text2_transform(self._pad)
+
+ def _apply_tickdir(self, tickdir):
+ # docstring inherited
+ super()._apply_tickdir(tickdir)
+ mark1, mark2 = {
+ 'out': (mlines.TICKDOWN, mlines.TICKUP),
+ 'in': (mlines.TICKUP, mlines.TICKDOWN),
+ 'inout': ('|', '|'),
+ }[self._tickdir]
+ self.tick1line.set_marker(mark1)
+ self.tick2line.set_marker(mark2)
+
+ def update_position(self, loc):
+ """Set the location of tick in data coords with scalar *loc*."""
+ self.tick1line.set_xdata((loc,))
+ self.tick2line.set_xdata((loc,))
+ self.gridline.set_xdata((loc,))
+ self.label1.set_x(loc)
+ self.label2.set_x(loc)
+ self._loc = loc
+ self.stale = True
+
+ def get_view_interval(self):
+ # docstring inherited
+ return self.axes.viewLim.intervalx
+
+
+class YTick(Tick):
+ """
+ Contains all the Artists needed to make a Y tick - the tick line,
+ the label text and the grid line
+ """
+ __name__ = 'ytick'
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ # x in axes coords, y in data coords
+ ax = self.axes
+ self.tick1line.set(
+ data=([0], [0]), transform=ax.get_yaxis_transform("tick1"))
+ self.tick2line.set(
+ data=([1], [0]), transform=ax.get_yaxis_transform("tick2"))
+ self.gridline.set(
+ data=([0, 1], [0, 0]), transform=ax.get_yaxis_transform("grid"))
+ # the y loc is 3 points below the min of y axis
+ trans, va, ha = self._get_text1_transform()
+ self.label1.set(
+ x=0, y=0,
+ verticalalignment=va, horizontalalignment=ha, transform=trans,
+ )
+ trans, va, ha = self._get_text2_transform()
+ self.label2.set(
+ x=1, y=0,
+ verticalalignment=va, horizontalalignment=ha, transform=trans,
+ )
+
+ def _get_text1_transform(self):
+ return self.axes.get_yaxis_text1_transform(self._pad)
+
+ def _get_text2_transform(self):
+ return self.axes.get_yaxis_text2_transform(self._pad)
+
+ def _apply_tickdir(self, tickdir):
+ # docstring inherited
+ super()._apply_tickdir(tickdir)
+ mark1, mark2 = {
+ 'out': (mlines.TICKLEFT, mlines.TICKRIGHT),
+ 'in': (mlines.TICKRIGHT, mlines.TICKLEFT),
+ 'inout': ('_', '_'),
+ }[self._tickdir]
+ self.tick1line.set_marker(mark1)
+ self.tick2line.set_marker(mark2)
+
+ def update_position(self, loc):
+ """Set the location of tick in data coords with scalar *loc*."""
+ self.tick1line.set_ydata((loc,))
+ self.tick2line.set_ydata((loc,))
+ self.gridline.set_ydata((loc,))
+ self.label1.set_y(loc)
+ self.label2.set_y(loc)
+ self._loc = loc
+ self.stale = True
+
+ def get_view_interval(self):
+ # docstring inherited
+ return self.axes.viewLim.intervaly
+
+
+class Ticker:
+ """
+ A container for the objects defining tick position and format.
+
+ Attributes
+ ----------
+ locator : `~matplotlib.ticker.Locator` subclass
+ Determines the positions of the ticks.
+ formatter : `~matplotlib.ticker.Formatter` subclass
+ Determines the format of the tick labels.
+ """
+
+ def __init__(self):
+ self._locator = None
+ self._formatter = None
+ self._locator_is_default = True
+ self._formatter_is_default = True
+
+ @property
+ def locator(self):
+ return self._locator
+
+ @locator.setter
+ def locator(self, locator):
+ if not isinstance(locator, mticker.Locator):
+ raise TypeError('locator must be a subclass of '
+ 'matplotlib.ticker.Locator')
+ self._locator = locator
+
+ @property
+ def formatter(self):
+ return self._formatter
+
+ @formatter.setter
+ def formatter(self, formatter):
+ if not isinstance(formatter, mticker.Formatter):
+ raise TypeError('formatter must be a subclass of '
+ 'matplotlib.ticker.Formatter')
+ self._formatter = formatter
+
+
+class _LazyTickList:
+ """
+ A descriptor for lazy instantiation of tick lists.
+
+ See comment above definition of the ``majorTicks`` and ``minorTicks``
+ attributes.
+ """
+
+ def __init__(self, major):
+ self._major = major
+
+ def __get__(self, instance, owner):
+ if instance is None:
+ return self
+ else:
+ # instance._get_tick() can itself try to access the majorTicks
+ # attribute (e.g. in certain projection classes which override
+ # e.g. get_xaxis_text1_transform). In order to avoid infinite
+ # recursion, first set the majorTicks on the instance temporarily
+ # to an empty lis. Then create the tick; note that _get_tick()
+ # may call reset_ticks(). Therefore, the final tick list is
+ # created and assigned afterwards.
+ if self._major:
+ instance.majorTicks = []
+ tick = instance._get_tick(major=True)
+ instance.majorTicks = [tick]
+ return instance.majorTicks
+ else:
+ instance.minorTicks = []
+ tick = instance._get_tick(major=False)
+ instance.minorTicks = [tick]
+ return instance.minorTicks
+
+
+class Axis(martist.Artist):
+ """
+ Base class for `.XAxis` and `.YAxis`.
+
+ Attributes
+ ----------
+ isDefault_label : bool
+
+ axes : `~matplotlib.axes.Axes`
+ The `~.axes.Axes` to which the Axis belongs.
+ major : `~matplotlib.axis.Ticker`
+ Determines the major tick positions and their label format.
+ minor : `~matplotlib.axis.Ticker`
+ Determines the minor tick positions and their label format.
+ callbacks : `~matplotlib.cbook.CallbackRegistry`
+
+ label : `~matplotlib.text.Text`
+ The axis label.
+ labelpad : float
+ The distance between the axis label and the tick labels.
+ Defaults to :rc:`axes.labelpad`.
+ offsetText : `~matplotlib.text.Text`
+ A `.Text` object containing the data offset of the ticks (if any).
+ pickradius : float
+ The acceptance radius for containment tests. See also `.Axis.contains`.
+ majorTicks : list of `.Tick`
+ The major ticks.
+
+ .. warning::
+
+ Ticks are not guaranteed to be persistent. Various operations
+ can create, delete and modify the Tick instances. There is an
+ imminent risk that changes to individual ticks will not
+ survive if you work on the figure further (including also
+ panning/zooming on a displayed figure).
+
+ Working on the individual ticks is a method of last resort.
+ Use `.set_tick_params` instead if possible.
+
+ minorTicks : list of `.Tick`
+ The minor ticks.
+ """
+ OFFSETTEXTPAD = 3
+ # The class used in _get_tick() to create tick instances. Must either be
+ # overwritten in subclasses, or subclasses must reimplement _get_tick().
+ _tick_class = None
+ converter = _api.deprecate_privatize_attribute(
+ "3.10",
+ alternative="get_converter and set_converter methods"
+ )
+
+ def __str__(self):
+ return "{}({},{})".format(
+ type(self).__name__, *self.axes.transAxes.transform((0, 0)))
+
+ def __init__(self, axes, *, pickradius=15, clear=True):
+ """
+ Parameters
+ ----------
+ axes : `~matplotlib.axes.Axes`
+ The `~.axes.Axes` to which the created Axis belongs.
+ pickradius : float
+ The acceptance radius for containment tests. See also
+ `.Axis.contains`.
+ clear : bool, default: True
+ Whether to clear the Axis on creation. This is not required, e.g., when
+ creating an Axis as part of an Axes, as ``Axes.clear`` will call
+ ``Axis.clear``.
+ .. versionadded:: 3.8
+ """
+ super().__init__()
+ self._remove_overlapping_locs = True
+
+ self.set_figure(axes.get_figure(root=False))
+
+ self.isDefault_label = True
+
+ self.axes = axes
+ self.major = Ticker()
+ self.minor = Ticker()
+ self.callbacks = cbook.CallbackRegistry(signals=["units"])
+
+ self._autolabelpos = True
+
+ self.label = mtext.Text(
+ np.nan, np.nan,
+ fontsize=mpl.rcParams['axes.labelsize'],
+ fontweight=mpl.rcParams['axes.labelweight'],
+ color=mpl.rcParams['axes.labelcolor'],
+ ) #: The `.Text` object of the axis label.
+
+ self._set_artist_props(self.label)
+ self.offsetText = mtext.Text(np.nan, np.nan)
+ self._set_artist_props(self.offsetText)
+
+ self.labelpad = mpl.rcParams['axes.labelpad']
+
+ self.pickradius = pickradius
+
+ # Initialize here for testing; later add API
+ self._major_tick_kw = dict()
+ self._minor_tick_kw = dict()
+
+ if clear:
+ self.clear()
+ else:
+ self._converter = None
+ self._converter_is_explicit = False
+ self.units = None
+
+ self._autoscale_on = True
+
+ @property
+ def isDefault_majloc(self):
+ return self.major._locator_is_default
+
+ @isDefault_majloc.setter
+ def isDefault_majloc(self, value):
+ self.major._locator_is_default = value
+
+ @property
+ def isDefault_majfmt(self):
+ return self.major._formatter_is_default
+
+ @isDefault_majfmt.setter
+ def isDefault_majfmt(self, value):
+ self.major._formatter_is_default = value
+
+ @property
+ def isDefault_minloc(self):
+ return self.minor._locator_is_default
+
+ @isDefault_minloc.setter
+ def isDefault_minloc(self, value):
+ self.minor._locator_is_default = value
+
+ @property
+ def isDefault_minfmt(self):
+ return self.minor._formatter_is_default
+
+ @isDefault_minfmt.setter
+ def isDefault_minfmt(self, value):
+ self.minor._formatter_is_default = value
+
+ def _get_shared_axes(self):
+ """Return Grouper of shared Axes for current axis."""
+ return self.axes._shared_axes[
+ self._get_axis_name()].get_siblings(self.axes)
+
+ def _get_shared_axis(self):
+ """Return list of shared axis for current axis."""
+ name = self._get_axis_name()
+ return [ax._axis_map[name] for ax in self._get_shared_axes()]
+
+ def _get_axis_name(self):
+ """Return the axis name."""
+ return next(name for name, axis in self.axes._axis_map.items()
+ if axis is self)
+
+ # During initialization, Axis objects often create ticks that are later
+ # unused; this turns out to be a very slow step. Instead, use a custom
+ # descriptor to make the tick lists lazy and instantiate them as needed.
+ majorTicks = _LazyTickList(major=True)
+ minorTicks = _LazyTickList(major=False)
+
+ def get_remove_overlapping_locs(self):
+ return self._remove_overlapping_locs
+
+ def set_remove_overlapping_locs(self, val):
+ self._remove_overlapping_locs = bool(val)
+
+ remove_overlapping_locs = property(
+ get_remove_overlapping_locs, set_remove_overlapping_locs,
+ doc=('If minor ticker locations that overlap with major '
+ 'ticker locations should be trimmed.'))
+
+ def set_label_coords(self, x, y, transform=None):
+ """
+ Set the coordinates of the label.
+
+ By default, the x coordinate of the y label and the y coordinate of the
+ x label are determined by the tick label bounding boxes, but this can
+ lead to poor alignment of multiple labels if there are multiple Axes.
+
+ You can also specify the coordinate system of the label with the
+ transform. If None, the default coordinate system will be the axes
+ coordinate system: (0, 0) is bottom left, (0.5, 0.5) is center, etc.
+ """
+ self._autolabelpos = False
+ if transform is None:
+ transform = self.axes.transAxes
+
+ self.label.set_transform(transform)
+ self.label.set_position((x, y))
+ self.stale = True
+
+ def get_transform(self):
+ """Return the transform used in the Axis' scale"""
+ return self._scale.get_transform()
+
+ def get_scale(self):
+ """Return this Axis' scale (as a str)."""
+ return self._scale.name
+
+ def _set_scale(self, value, **kwargs):
+ if not isinstance(value, mscale.ScaleBase):
+ self._scale = mscale.scale_factory(value, self, **kwargs)
+ else:
+ self._scale = value
+ self._scale.set_default_locators_and_formatters(self)
+
+ self.isDefault_majloc = True
+ self.isDefault_minloc = True
+ self.isDefault_majfmt = True
+ self.isDefault_minfmt = True
+
+ # This method is directly wrapped by Axes.set_{x,y}scale.
+ def _set_axes_scale(self, value, **kwargs):
+ """
+ Set this Axis' scale.
+
+ Parameters
+ ----------
+ value : str or `.ScaleBase`
+ The axis scale type to apply. Valid string values are the names of scale
+ classes ("linear", "log", "function",...). These may be the names of any
+ of the :ref:`built-in scales` or of any custom scales
+ registered using `matplotlib.scale.register_scale`.
+
+ **kwargs
+ If *value* is a string, keywords are passed to the instantiation method of
+ the respective class.
+ """
+ name = self._get_axis_name()
+ old_default_lims = (self.get_major_locator()
+ .nonsingular(-np.inf, np.inf))
+ for ax in self._get_shared_axes():
+ ax._axis_map[name]._set_scale(value, **kwargs)
+ ax._update_transScale()
+ ax.stale = True
+ new_default_lims = (self.get_major_locator()
+ .nonsingular(-np.inf, np.inf))
+ if old_default_lims != new_default_lims:
+ # Force autoscaling now, to take advantage of the scale locator's
+ # nonsingular() before it possibly gets swapped out by the user.
+ self.axes.autoscale_view(
+ **{f"scale{k}": k == name for k in self.axes._axis_names})
+
+ def limit_range_for_scale(self, vmin, vmax):
+ """
+ Return the range *vmin*, *vmax*, restricted to the domain supported by the
+ current scale.
+ """
+ return self._scale.limit_range_for_scale(vmin, vmax, self.get_minpos())
+
+ def _get_autoscale_on(self):
+ """Return whether this Axis is autoscaled."""
+ return self._autoscale_on
+
+ def _set_autoscale_on(self, b):
+ """
+ Set whether this Axis is autoscaled when drawing or by `.Axes.autoscale_view`.
+
+ If b is None, then the value is not changed.
+
+ Parameters
+ ----------
+ b : bool
+ """
+ if b is not None:
+ self._autoscale_on = b
+
+ def get_children(self):
+ return [self.label, self.offsetText,
+ *self.get_major_ticks(), *self.get_minor_ticks()]
+
+ def _reset_major_tick_kw(self):
+ self._major_tick_kw.clear()
+ self._major_tick_kw['gridOn'] = (
+ mpl.rcParams['axes.grid'] and
+ mpl.rcParams['axes.grid.which'] in ('both', 'major'))
+
+ def _reset_minor_tick_kw(self):
+ self._minor_tick_kw.clear()
+ self._minor_tick_kw['gridOn'] = (
+ mpl.rcParams['axes.grid'] and
+ mpl.rcParams['axes.grid.which'] in ('both', 'minor'))
+
+ def clear(self):
+ """
+ Clear the axis.
+
+ This resets axis properties to their default values:
+
+ - the label
+ - the scale
+ - locators, formatters and ticks
+ - major and minor grid
+ - units
+ - registered callbacks
+ """
+ self.label._reset_visual_defaults()
+ # The above resets the label formatting using text rcParams,
+ # so we then update the formatting using axes rcParams
+ self.label.set_color(mpl.rcParams['axes.labelcolor'])
+ self.label.set_fontsize(mpl.rcParams['axes.labelsize'])
+ self.label.set_fontweight(mpl.rcParams['axes.labelweight'])
+ self.offsetText._reset_visual_defaults()
+ self.labelpad = mpl.rcParams['axes.labelpad']
+
+ self._init()
+
+ self._set_scale('linear')
+
+ # Clear the callback registry for this axis, or it may "leak"
+ self.callbacks = cbook.CallbackRegistry(signals=["units"])
+
+ # whether the grids are on
+ self._major_tick_kw['gridOn'] = (
+ mpl.rcParams['axes.grid'] and
+ mpl.rcParams['axes.grid.which'] in ('both', 'major'))
+ self._minor_tick_kw['gridOn'] = (
+ mpl.rcParams['axes.grid'] and
+ mpl.rcParams['axes.grid.which'] in ('both', 'minor'))
+ self.reset_ticks()
+
+ self._converter = None
+ self._converter_is_explicit = False
+ self.units = None
+ self.stale = True
+
+ def reset_ticks(self):
+ """
+ Re-initialize the major and minor Tick lists.
+
+ Each list starts with a single fresh Tick.
+ """
+ # Restore the lazy tick lists.
+ try:
+ del self.majorTicks
+ except AttributeError:
+ pass
+ try:
+ del self.minorTicks
+ except AttributeError:
+ pass
+ try:
+ self.set_clip_path(self.axes.patch)
+ except AttributeError:
+ pass
+
+ def minorticks_on(self):
+ """
+ Display default minor ticks on the Axis, depending on the scale
+ (`~.axis.Axis.get_scale`).
+
+ Scales use specific minor locators:
+
+ - log: `~.LogLocator`
+ - symlog: `~.SymmetricalLogLocator`
+ - asinh: `~.AsinhLocator`
+ - logit: `~.LogitLocator`
+ - default: `~.AutoMinorLocator`
+
+ Displaying minor ticks may reduce performance; you may turn them off
+ using `minorticks_off()` if drawing speed is a problem.
+ """
+ scale = self.get_scale()
+ if scale == 'log':
+ s = self._scale
+ self.set_minor_locator(mticker.LogLocator(s.base, s.subs))
+ elif scale == 'symlog':
+ s = self._scale
+ self.set_minor_locator(
+ mticker.SymmetricalLogLocator(s._transform, s.subs))
+ elif scale == 'asinh':
+ s = self._scale
+ self.set_minor_locator(
+ mticker.AsinhLocator(s.linear_width, base=s._base,
+ subs=s._subs))
+ elif scale == 'logit':
+ self.set_minor_locator(mticker.LogitLocator(minor=True))
+ else:
+ self.set_minor_locator(mticker.AutoMinorLocator())
+
+ def minorticks_off(self):
+ """Remove minor ticks from the Axis."""
+ self.set_minor_locator(mticker.NullLocator())
+
+ def set_tick_params(self, which='major', reset=False, **kwargs):
+ """
+ Set appearance parameters for ticks, ticklabels, and gridlines.
+
+ For documentation of keyword arguments, see
+ :meth:`matplotlib.axes.Axes.tick_params`.
+
+ See Also
+ --------
+ .Axis.get_tick_params
+ View the current style settings for ticks, ticklabels, and
+ gridlines.
+ """
+ _api.check_in_list(['major', 'minor', 'both'], which=which)
+ kwtrans = self._translate_tick_params(kwargs)
+
+ # the kwargs are stored in self._major/minor_tick_kw so that any
+ # future new ticks will automatically get them
+ if reset:
+ if which in ['major', 'both']:
+ self._reset_major_tick_kw()
+ self._major_tick_kw.update(kwtrans)
+ if which in ['minor', 'both']:
+ self._reset_minor_tick_kw()
+ self._minor_tick_kw.update(kwtrans)
+ self.reset_ticks()
+ else:
+ if which in ['major', 'both']:
+ self._major_tick_kw.update(kwtrans)
+ for tick in self.majorTicks:
+ tick._apply_params(**kwtrans)
+ if which in ['minor', 'both']:
+ self._minor_tick_kw.update(kwtrans)
+ for tick in self.minorTicks:
+ tick._apply_params(**kwtrans)
+ # labelOn and labelcolor also apply to the offset text.
+ if 'label1On' in kwtrans or 'label2On' in kwtrans:
+ self.offsetText.set_visible(
+ self._major_tick_kw.get('label1On', False)
+ or self._major_tick_kw.get('label2On', False))
+ if 'labelcolor' in kwtrans:
+ self.offsetText.set_color(kwtrans['labelcolor'])
+
+ self.stale = True
+
+ def get_tick_params(self, which='major'):
+ """
+ Get appearance parameters for ticks, ticklabels, and gridlines.
+
+ .. versionadded:: 3.7
+
+ Parameters
+ ----------
+ which : {'major', 'minor'}, default: 'major'
+ The group of ticks for which the parameters are retrieved.
+
+ Returns
+ -------
+ dict
+ Properties for styling tick elements added to the axis.
+
+ Notes
+ -----
+ This method returns the appearance parameters for styling *new*
+ elements added to this axis and may be different from the values
+ on current elements if they were modified directly by the user
+ (e.g., via ``set_*`` methods on individual tick objects).
+
+ Examples
+ --------
+ ::
+
+ >>> ax.yaxis.set_tick_params(labelsize=30, labelcolor='red',
+ ... direction='out', which='major')
+ >>> ax.yaxis.get_tick_params(which='major')
+ {'direction': 'out',
+ 'left': True,
+ 'right': False,
+ 'labelleft': True,
+ 'labelright': False,
+ 'gridOn': False,
+ 'labelsize': 30,
+ 'labelcolor': 'red'}
+ >>> ax.yaxis.get_tick_params(which='minor')
+ {'left': True,
+ 'right': False,
+ 'labelleft': True,
+ 'labelright': False,
+ 'gridOn': False}
+
+
+ """
+ _api.check_in_list(['major', 'minor'], which=which)
+ if which == 'major':
+ return self._translate_tick_params(
+ self._major_tick_kw, reverse=True
+ )
+ return self._translate_tick_params(self._minor_tick_kw, reverse=True)
+
+ @classmethod
+ def _translate_tick_params(cls, kw, reverse=False):
+ """
+ Translate the kwargs supported by `.Axis.set_tick_params` to kwargs
+ supported by `.Tick._apply_params`.
+
+ In particular, this maps axis specific names like 'top', 'left'
+ to the generic tick1, tick2 logic of the axis. Additionally, there
+ are some other name translations.
+
+ Returns a new dict of translated kwargs.
+
+ Note: Use reverse=True to translate from those supported by
+ `.Tick._apply_params` back to those supported by
+ `.Axis.set_tick_params`.
+ """
+ kw_ = {**kw}
+
+ # The following lists may be moved to a more accessible location.
+ allowed_keys = [
+ 'size', 'width', 'color', 'tickdir', 'pad',
+ 'labelsize', 'labelcolor', 'labelfontfamily', 'zorder', 'gridOn',
+ 'tick1On', 'tick2On', 'label1On', 'label2On',
+ 'length', 'direction', 'left', 'bottom', 'right', 'top',
+ 'labelleft', 'labelbottom', 'labelright', 'labeltop',
+ 'labelrotation',
+ *_gridline_param_names]
+
+ keymap = {
+ # tick_params key -> axis key
+ 'length': 'size',
+ 'direction': 'tickdir',
+ 'rotation': 'labelrotation',
+ 'left': 'tick1On',
+ 'bottom': 'tick1On',
+ 'right': 'tick2On',
+ 'top': 'tick2On',
+ 'labelleft': 'label1On',
+ 'labelbottom': 'label1On',
+ 'labelright': 'label2On',
+ 'labeltop': 'label2On',
+ }
+ if reverse:
+ kwtrans = {}
+ is_x_axis = cls.axis_name == 'x'
+ y_axis_keys = ['left', 'right', 'labelleft', 'labelright']
+ for oldkey, newkey in keymap.items():
+ if newkey in kw_:
+ if is_x_axis and oldkey in y_axis_keys:
+ continue
+ else:
+ kwtrans[oldkey] = kw_.pop(newkey)
+ else:
+ kwtrans = {
+ newkey: kw_.pop(oldkey)
+ for oldkey, newkey in keymap.items() if oldkey in kw_
+ }
+ if 'colors' in kw_:
+ c = kw_.pop('colors')
+ kwtrans['color'] = c
+ kwtrans['labelcolor'] = c
+ # Maybe move the checking up to the caller of this method.
+ for key in kw_:
+ if key not in allowed_keys:
+ raise ValueError(
+ "keyword %s is not recognized; valid keywords are %s"
+ % (key, allowed_keys))
+ kwtrans.update(kw_)
+ return kwtrans
+
+ def set_clip_path(self, path, transform=None):
+ super().set_clip_path(path, transform)
+ for child in self.majorTicks + self.minorTicks:
+ child.set_clip_path(path, transform)
+ self.stale = True
+
+ def get_view_interval(self):
+ """Return the ``(min, max)`` view limits of this axis."""
+ raise NotImplementedError('Derived must override')
+
+ def set_view_interval(self, vmin, vmax, ignore=False):
+ """
+ Set the axis view limits. This method is for internal use; Matplotlib
+ users should typically use e.g. `~.Axes.set_xlim` or `~.Axes.set_ylim`.
+
+ If *ignore* is False (the default), this method will never reduce the
+ preexisting view limits, only expand them if *vmin* or *vmax* are not
+ within them. Moreover, the order of *vmin* and *vmax* does not matter;
+ the orientation of the axis will not change.
+
+ If *ignore* is True, the view limits will be set exactly to ``(vmin,
+ vmax)`` in that order.
+ """
+ raise NotImplementedError('Derived must override')
+
+ def get_data_interval(self):
+ """Return the ``(min, max)`` data limits of this axis."""
+ raise NotImplementedError('Derived must override')
+
+ def set_data_interval(self, vmin, vmax, ignore=False):
+ """
+ Set the axis data limits. This method is for internal use.
+
+ If *ignore* is False (the default), this method will never reduce the
+ preexisting data limits, only expand them if *vmin* or *vmax* are not
+ within them. Moreover, the order of *vmin* and *vmax* does not matter;
+ the orientation of the axis will not change.
+
+ If *ignore* is True, the data limits will be set exactly to ``(vmin,
+ vmax)`` in that order.
+ """
+ raise NotImplementedError('Derived must override')
+
+ def get_inverted(self):
+ """
+ Return whether this Axis is oriented in the "inverse" direction.
+
+ The "normal" direction is increasing to the right for the x-axis and to
+ the top for the y-axis; the "inverse" direction is increasing to the
+ left for the x-axis and to the bottom for the y-axis.
+ """
+ low, high = self.get_view_interval()
+ return high < low
+
+ def set_inverted(self, inverted):
+ """
+ Set whether this Axis is oriented in the "inverse" direction.
+
+ The "normal" direction is increasing to the right for the x-axis and to
+ the top for the y-axis; the "inverse" direction is increasing to the
+ left for the x-axis and to the bottom for the y-axis.
+ """
+ a, b = self.get_view_interval()
+ # cast to bool to avoid bad interaction between python 3.8 and np.bool_
+ self._set_lim(*sorted((a, b), reverse=bool(inverted)), auto=None)
+
+ def set_default_intervals(self):
+ """
+ Set the default limits for the axis data and view interval if they
+ have not been not mutated yet.
+ """
+ # this is mainly in support of custom object plotting. For
+ # example, if someone passes in a datetime object, we do not
+ # know automagically how to set the default min/max of the
+ # data and view limits. The unit conversion AxisInfo
+ # interface provides a hook for custom types to register
+ # default limits through the AxisInfo.default_limits
+ # attribute, and the derived code below will check for that
+ # and use it if it's available (else just use 0..1)
+
+ def _set_lim(self, v0, v1, *, emit=True, auto):
+ """
+ Set view limits.
+
+ This method is a helper for the Axes ``set_xlim``, ``set_ylim``, and
+ ``set_zlim`` methods.
+
+ Parameters
+ ----------
+ v0, v1 : float
+ The view limits. (Passing *v0* as a (low, high) pair is not
+ supported; normalization must occur in the Axes setters.)
+ emit : bool, default: True
+ Whether to notify observers of limit change.
+ auto : bool or None, default: False
+ Whether to turn on autoscaling of the x-axis. True turns on, False
+ turns off, None leaves unchanged.
+ """
+ name = self._get_axis_name()
+
+ self.axes._process_unit_info([(name, (v0, v1))], convert=False)
+ v0 = self.axes._validate_converted_limits(v0, self.convert_units)
+ v1 = self.axes._validate_converted_limits(v1, self.convert_units)
+
+ if v0 is None or v1 is None:
+ # Axes init calls set_xlim(0, 1) before get_xlim() can be called,
+ # so only grab the limits if we really need them.
+ old0, old1 = self.get_view_interval()
+ if v0 is None:
+ v0 = old0
+ if v1 is None:
+ v1 = old1
+
+ if self.get_scale() == 'log' and (v0 <= 0 or v1 <= 0):
+ # Axes init calls set_xlim(0, 1) before get_xlim() can be called,
+ # so only grab the limits if we really need them.
+ old0, old1 = self.get_view_interval()
+ if v0 <= 0:
+ _api.warn_external(f"Attempt to set non-positive {name}lim on "
+ f"a log-scaled axis will be ignored.")
+ v0 = old0
+ if v1 <= 0:
+ _api.warn_external(f"Attempt to set non-positive {name}lim on "
+ f"a log-scaled axis will be ignored.")
+ v1 = old1
+ if v0 == v1:
+ _api.warn_external(
+ f"Attempting to set identical low and high {name}lims "
+ f"makes transformation singular; automatically expanding.")
+ reverse = bool(v0 > v1) # explicit cast needed for python3.8+np.bool_.
+ v0, v1 = self.get_major_locator().nonsingular(v0, v1)
+ v0, v1 = self.limit_range_for_scale(v0, v1)
+ v0, v1 = sorted([v0, v1], reverse=bool(reverse))
+
+ self.set_view_interval(v0, v1, ignore=True)
+ # Mark viewlims as no longer stale without triggering an autoscale.
+ for ax in self._get_shared_axes():
+ ax._stale_viewlims[name] = False
+ self._set_autoscale_on(auto)
+
+ if emit:
+ self.axes.callbacks.process(f"{name}lim_changed", self.axes)
+ # Call all of the other Axes that are shared with this one
+ for other in self._get_shared_axes():
+ if other is self.axes:
+ continue
+ other._axis_map[name]._set_lim(v0, v1, emit=False, auto=auto)
+ if emit:
+ other.callbacks.process(f"{name}lim_changed", other)
+ if ((other_fig := other.get_figure(root=False)) !=
+ self.get_figure(root=False)):
+ other_fig.canvas.draw_idle()
+
+ self.stale = True
+ return v0, v1
+
+ def _set_artist_props(self, a):
+ if a is None:
+ return
+ a.set_figure(self.get_figure(root=False))
+
+ def _update_ticks(self):
+ """
+ Update ticks (position and labels) using the current data interval of
+ the axes. Return the list of ticks that will be drawn.
+ """
+ major_locs = self.get_majorticklocs()
+ major_labels = self.major.formatter.format_ticks(major_locs)
+ major_ticks = self.get_major_ticks(len(major_locs))
+ for tick, loc, label in zip(major_ticks, major_locs, major_labels):
+ tick.update_position(loc)
+ tick.label1.set_text(label)
+ tick.label2.set_text(label)
+ minor_locs = self.get_minorticklocs()
+ minor_labels = self.minor.formatter.format_ticks(minor_locs)
+ minor_ticks = self.get_minor_ticks(len(minor_locs))
+ for tick, loc, label in zip(minor_ticks, minor_locs, minor_labels):
+ tick.update_position(loc)
+ tick.label1.set_text(label)
+ tick.label2.set_text(label)
+ ticks = [*major_ticks, *minor_ticks]
+
+ view_low, view_high = self.get_view_interval()
+ if view_low > view_high:
+ view_low, view_high = view_high, view_low
+
+ if (hasattr(self, "axes") and self.axes.name == '3d'
+ and mpl.rcParams['axes3d.automargin']):
+ # In mpl3.8, the margin was 1/48. Due to the change in automargin
+ # behavior in mpl3.9, we need to adjust this to compensate for a
+ # zoom factor of 2/48, giving us a 23/24 modifier. So the new
+ # margin is 0.019965277777777776 = 1/48*23/24.
+ margin = 0.019965277777777776
+ delta = view_high - view_low
+ view_high = view_high - delta * margin
+ view_low = view_low + delta * margin
+
+ interval_t = self.get_transform().transform([view_low, view_high])
+
+ ticks_to_draw = []
+ for tick in ticks:
+ try:
+ loc_t = self.get_transform().transform(tick.get_loc())
+ except AssertionError:
+ # transforms.transform doesn't allow masked values but
+ # some scales might make them, so we need this try/except.
+ pass
+ else:
+ if mtransforms._interval_contains_close(interval_t, loc_t):
+ ticks_to_draw.append(tick)
+
+ return ticks_to_draw
+
+ def _get_ticklabel_bboxes(self, ticks, renderer=None):
+ """Return lists of bboxes for ticks' label1's and label2's."""
+ if renderer is None:
+ renderer = self.get_figure(root=True)._get_renderer()
+ return ([tick.label1.get_window_extent(renderer)
+ for tick in ticks if tick.label1.get_visible()],
+ [tick.label2.get_window_extent(renderer)
+ for tick in ticks if tick.label2.get_visible()])
+
+ def get_tightbbox(self, renderer=None, *, for_layout_only=False):
+ """
+ Return a bounding box that encloses the axis. It only accounts
+ tick labels, axis label, and offsetText.
+
+ If *for_layout_only* is True, then the width of the label (if this
+ is an x-axis) or the height of the label (if this is a y-axis) is
+ collapsed to near zero. This allows tight/constrained_layout to ignore
+ too-long labels when doing their layout.
+ """
+ if not self.get_visible() or for_layout_only and not self.get_in_layout():
+ return
+ if renderer is None:
+ renderer = self.get_figure(root=True)._get_renderer()
+ ticks_to_draw = self._update_ticks()
+
+ self._update_label_position(renderer)
+
+ # go back to just this axis's tick labels
+ tlb1, tlb2 = self._get_ticklabel_bboxes(ticks_to_draw, renderer)
+
+ self._update_offset_text_position(tlb1, tlb2)
+ self.offsetText.set_text(self.major.formatter.get_offset())
+
+ bboxes = [
+ *(a.get_window_extent(renderer)
+ for a in [self.offsetText]
+ if a.get_visible()),
+ *tlb1, *tlb2,
+ ]
+ # take care of label
+ if self.label.get_visible():
+ bb = self.label.get_window_extent(renderer)
+ # for constrained/tight_layout, we want to ignore the label's
+ # width/height because the adjustments they make can't be improved.
+ # this code collapses the relevant direction
+ if for_layout_only:
+ if self.axis_name == "x" and bb.width > 0:
+ bb.x0 = (bb.x0 + bb.x1) / 2 - 0.5
+ bb.x1 = bb.x0 + 1.0
+ if self.axis_name == "y" and bb.height > 0:
+ bb.y0 = (bb.y0 + bb.y1) / 2 - 0.5
+ bb.y1 = bb.y0 + 1.0
+ bboxes.append(bb)
+ bboxes = [b for b in bboxes
+ if 0 < b.width < np.inf and 0 < b.height < np.inf]
+ if bboxes:
+ return mtransforms.Bbox.union(bboxes)
+ else:
+ return None
+
+ def get_tick_padding(self):
+ values = []
+ if len(self.majorTicks):
+ values.append(self.majorTicks[0].get_tick_padding())
+ if len(self.minorTicks):
+ values.append(self.minorTicks[0].get_tick_padding())
+ return max(values, default=0)
+
+ @martist.allow_rasterization
+ def draw(self, renderer):
+ # docstring inherited
+
+ if not self.get_visible():
+ return
+ renderer.open_group(__name__, gid=self.get_gid())
+
+ ticks_to_draw = self._update_ticks()
+ tlb1, tlb2 = self._get_ticklabel_bboxes(ticks_to_draw, renderer)
+
+ for tick in ticks_to_draw:
+ tick.draw(renderer)
+
+ # Shift label away from axes to avoid overlapping ticklabels.
+ self._update_label_position(renderer)
+ self.label.draw(renderer)
+
+ self._update_offset_text_position(tlb1, tlb2)
+ self.offsetText.set_text(self.major.formatter.get_offset())
+ self.offsetText.draw(renderer)
+
+ renderer.close_group(__name__)
+ self.stale = False
+
+ def get_gridlines(self):
+ r"""Return this Axis' grid lines as a list of `.Line2D`\s."""
+ ticks = self.get_major_ticks()
+ return cbook.silent_list('Line2D gridline',
+ [tick.gridline for tick in ticks])
+
+ def set_label(self, s):
+ """Assigning legend labels is not supported. Raises RuntimeError."""
+ raise RuntimeError(
+ "A legend label cannot be assigned to an Axis. Did you mean to "
+ "set the axis label via set_label_text()?")
+
+ def get_label(self):
+ """
+ Return the axis label as a Text instance.
+
+ .. admonition:: Discouraged
+
+ This overrides `.Artist.get_label`, which is for legend labels, with a new
+ semantic. It is recommended to use the attribute ``Axis.label`` instead.
+ """
+ return self.label
+
+ def get_offset_text(self):
+ """Return the axis offsetText as a Text instance."""
+ return self.offsetText
+
+ def get_pickradius(self):
+ """Return the depth of the axis used by the picker."""
+ return self._pickradius
+
+ def get_majorticklabels(self):
+ """Return this Axis' major tick labels, as a list of `~.text.Text`."""
+ self._update_ticks()
+ ticks = self.get_major_ticks()
+ labels1 = [tick.label1 for tick in ticks if tick.label1.get_visible()]
+ labels2 = [tick.label2 for tick in ticks if tick.label2.get_visible()]
+ return labels1 + labels2
+
+ def get_minorticklabels(self):
+ """Return this Axis' minor tick labels, as a list of `~.text.Text`."""
+ self._update_ticks()
+ ticks = self.get_minor_ticks()
+ labels1 = [tick.label1 for tick in ticks if tick.label1.get_visible()]
+ labels2 = [tick.label2 for tick in ticks if tick.label2.get_visible()]
+ return labels1 + labels2
+
+ def get_ticklabels(self, minor=False, which=None):
+ """
+ Get this Axis' tick labels.
+
+ Parameters
+ ----------
+ minor : bool
+ Whether to return the minor or the major ticklabels.
+
+ which : None, ('minor', 'major', 'both')
+ Overrides *minor*.
+
+ Selects which ticklabels to return
+
+ Returns
+ -------
+ list of `~matplotlib.text.Text`
+ """
+ if which is not None:
+ if which == 'minor':
+ return self.get_minorticklabels()
+ elif which == 'major':
+ return self.get_majorticklabels()
+ elif which == 'both':
+ return self.get_majorticklabels() + self.get_minorticklabels()
+ else:
+ _api.check_in_list(['major', 'minor', 'both'], which=which)
+ if minor:
+ return self.get_minorticklabels()
+ return self.get_majorticklabels()
+
+ def get_majorticklines(self):
+ r"""Return this Axis' major tick lines as a list of `.Line2D`\s."""
+ lines = []
+ ticks = self.get_major_ticks()
+ for tick in ticks:
+ lines.append(tick.tick1line)
+ lines.append(tick.tick2line)
+ return cbook.silent_list('Line2D ticklines', lines)
+
+ def get_minorticklines(self):
+ r"""Return this Axis' minor tick lines as a list of `.Line2D`\s."""
+ lines = []
+ ticks = self.get_minor_ticks()
+ for tick in ticks:
+ lines.append(tick.tick1line)
+ lines.append(tick.tick2line)
+ return cbook.silent_list('Line2D ticklines', lines)
+
+ def get_ticklines(self, minor=False):
+ r"""Return this Axis' tick lines as a list of `.Line2D`\s."""
+ if minor:
+ return self.get_minorticklines()
+ return self.get_majorticklines()
+
+ def get_majorticklocs(self):
+ """Return this Axis' major tick locations in data coordinates."""
+ return self.major.locator()
+
+ def get_minorticklocs(self):
+ """Return this Axis' minor tick locations in data coordinates."""
+ # Remove minor ticks duplicating major ticks.
+ minor_locs = np.asarray(self.minor.locator())
+ if self.remove_overlapping_locs:
+ major_locs = self.major.locator()
+ transform = self._scale.get_transform()
+ tr_minor_locs = transform.transform(minor_locs)
+ tr_major_locs = transform.transform(major_locs)
+ lo, hi = sorted(transform.transform(self.get_view_interval()))
+ # Use the transformed view limits as scale. 1e-5 is the default
+ # rtol for np.isclose.
+ tol = (hi - lo) * 1e-5
+ mask = np.isclose(tr_minor_locs[:, None], tr_major_locs[None, :],
+ atol=tol, rtol=0).any(axis=1)
+ minor_locs = minor_locs[~mask]
+ return minor_locs
+
+ def get_ticklocs(self, *, minor=False):
+ """
+ Return this Axis' tick locations in data coordinates.
+
+ The locations are not clipped to the current axis limits and hence
+ may contain locations that are not visible in the output.
+
+ Parameters
+ ----------
+ minor : bool, default: False
+ True to return the minor tick directions,
+ False to return the major tick directions.
+
+ Returns
+ -------
+ array of tick locations
+ """
+ return self.get_minorticklocs() if minor else self.get_majorticklocs()
+
+ def get_ticks_direction(self, minor=False):
+ """
+ Return an array of this Axis' tick directions.
+
+ Parameters
+ ----------
+ minor : bool, default: False
+ True to return the minor tick directions,
+ False to return the major tick directions.
+
+ Returns
+ -------
+ array of tick directions
+ """
+ if minor:
+ return np.array(
+ [tick._tickdir for tick in self.get_minor_ticks()])
+ else:
+ return np.array(
+ [tick._tickdir for tick in self.get_major_ticks()])
+
+ def _get_tick(self, major):
+ """Return the default tick instance."""
+ if self._tick_class is None:
+ raise NotImplementedError(
+ f"The Axis subclass {self.__class__.__name__} must define "
+ "_tick_class or reimplement _get_tick()")
+ tick_kw = self._major_tick_kw if major else self._minor_tick_kw
+ return self._tick_class(self.axes, 0, major=major, **tick_kw)
+
+ def _get_tick_label_size(self, axis_name):
+ """
+ Return the text size of tick labels for this Axis.
+
+ This is a convenience function to avoid having to create a `Tick` in
+ `.get_tick_space`, since it is expensive.
+ """
+ tick_kw = self._major_tick_kw
+ size = tick_kw.get('labelsize',
+ mpl.rcParams[f'{axis_name}tick.labelsize'])
+ return mtext.FontProperties(size=size).get_size_in_points()
+
+ def _copy_tick_props(self, src, dest):
+ """Copy the properties from *src* tick to *dest* tick."""
+ if src is None or dest is None:
+ return
+ dest.label1.update_from(src.label1)
+ dest.label2.update_from(src.label2)
+ dest.tick1line.update_from(src.tick1line)
+ dest.tick2line.update_from(src.tick2line)
+ dest.gridline.update_from(src.gridline)
+ dest.update_from(src)
+ dest._loc = src._loc
+ dest._size = src._size
+ dest._width = src._width
+ dest._base_pad = src._base_pad
+ dest._labelrotation = src._labelrotation
+ dest._zorder = src._zorder
+ dest._tickdir = src._tickdir
+
+ def get_label_text(self):
+ """Get the text of the label."""
+ return self.label.get_text()
+
+ def get_major_locator(self):
+ """Get the locator of the major ticker."""
+ return self.major.locator
+
+ def get_minor_locator(self):
+ """Get the locator of the minor ticker."""
+ return self.minor.locator
+
+ def get_major_formatter(self):
+ """Get the formatter of the major ticker."""
+ return self.major.formatter
+
+ def get_minor_formatter(self):
+ """Get the formatter of the minor ticker."""
+ return self.minor.formatter
+
+ def get_major_ticks(self, numticks=None):
+ r"""
+ Return the list of major `.Tick`\s.
+
+ .. warning::
+
+ Ticks are not guaranteed to be persistent. Various operations
+ can create, delete and modify the Tick instances. There is an
+ imminent risk that changes to individual ticks will not
+ survive if you work on the figure further (including also
+ panning/zooming on a displayed figure).
+
+ Working on the individual ticks is a method of last resort.
+ Use `.set_tick_params` instead if possible.
+ """
+ if numticks is None:
+ numticks = len(self.get_majorticklocs())
+
+ while len(self.majorTicks) < numticks:
+ # Update the new tick label properties from the old.
+ tick = self._get_tick(major=True)
+ self.majorTicks.append(tick)
+ self._copy_tick_props(self.majorTicks[0], tick)
+
+ return self.majorTicks[:numticks]
+
+ def get_minor_ticks(self, numticks=None):
+ r"""
+ Return the list of minor `.Tick`\s.
+
+ .. warning::
+
+ Ticks are not guaranteed to be persistent. Various operations
+ can create, delete and modify the Tick instances. There is an
+ imminent risk that changes to individual ticks will not
+ survive if you work on the figure further (including also
+ panning/zooming on a displayed figure).
+
+ Working on the individual ticks is a method of last resort.
+ Use `.set_tick_params` instead if possible.
+ """
+ if numticks is None:
+ numticks = len(self.get_minorticklocs())
+
+ while len(self.minorTicks) < numticks:
+ # Update the new tick label properties from the old.
+ tick = self._get_tick(major=False)
+ self.minorTicks.append(tick)
+ self._copy_tick_props(self.minorTicks[0], tick)
+
+ return self.minorTicks[:numticks]
+
+ def grid(self, visible=None, which='major', **kwargs):
+ """
+ Configure the grid lines.
+
+ Parameters
+ ----------
+ visible : bool or None
+ Whether to show the grid lines. If any *kwargs* are supplied, it
+ is assumed you want the grid on and *visible* will be set to True.
+
+ If *visible* is *None* and there are no *kwargs*, this toggles the
+ visibility of the lines.
+
+ which : {'major', 'minor', 'both'}
+ The grid lines to apply the changes on.
+
+ **kwargs : `~matplotlib.lines.Line2D` properties
+ Define the line properties of the grid, e.g.::
+
+ grid(color='r', linestyle='-', linewidth=2)
+ """
+ if kwargs:
+ if visible is None:
+ visible = True
+ elif not visible: # something false-like but not None
+ _api.warn_external('First parameter to grid() is false, '
+ 'but line properties are supplied. The '
+ 'grid will be enabled.')
+ visible = True
+ which = which.lower()
+ _api.check_in_list(['major', 'minor', 'both'], which=which)
+ gridkw = {f'grid_{name}': value for name, value in kwargs.items()}
+ if which in ['minor', 'both']:
+ gridkw['gridOn'] = (not self._minor_tick_kw['gridOn']
+ if visible is None else visible)
+ self.set_tick_params(which='minor', **gridkw)
+ if which in ['major', 'both']:
+ gridkw['gridOn'] = (not self._major_tick_kw['gridOn']
+ if visible is None else visible)
+ self.set_tick_params(which='major', **gridkw)
+ self.stale = True
+
+ def update_units(self, data):
+ """
+ Introspect *data* for units converter and update the
+ ``axis.get_converter`` instance if necessary. Return *True*
+ if *data* is registered for unit conversion.
+ """
+ if not self._converter_is_explicit:
+ converter = munits.registry.get_converter(data)
+ else:
+ converter = self._converter
+
+ if converter is None:
+ return False
+
+ neednew = self._converter != converter
+ self._set_converter(converter)
+ default = self._converter.default_units(data, self)
+ if default is not None and self.units is None:
+ self.set_units(default)
+
+ elif neednew:
+ self._update_axisinfo()
+ self.stale = True
+ return True
+
+ def _update_axisinfo(self):
+ """
+ Check the axis converter for the stored units to see if the
+ axis info needs to be updated.
+ """
+ if self._converter is None:
+ return
+
+ info = self._converter.axisinfo(self.units, self)
+
+ if info is None:
+ return
+ if info.majloc is not None and \
+ self.major.locator != info.majloc and self.isDefault_majloc:
+ self.set_major_locator(info.majloc)
+ self.isDefault_majloc = True
+ if info.minloc is not None and \
+ self.minor.locator != info.minloc and self.isDefault_minloc:
+ self.set_minor_locator(info.minloc)
+ self.isDefault_minloc = True
+ if info.majfmt is not None and \
+ self.major.formatter != info.majfmt and self.isDefault_majfmt:
+ self.set_major_formatter(info.majfmt)
+ self.isDefault_majfmt = True
+ if info.minfmt is not None and \
+ self.minor.formatter != info.minfmt and self.isDefault_minfmt:
+ self.set_minor_formatter(info.minfmt)
+ self.isDefault_minfmt = True
+ if info.label is not None and self.isDefault_label:
+ self.set_label_text(info.label)
+ self.isDefault_label = True
+
+ self.set_default_intervals()
+
+ def have_units(self):
+ return self._converter is not None or self.units is not None
+
+ def convert_units(self, x):
+ # If x is natively supported by Matplotlib, doesn't need converting
+ if munits._is_natively_supported(x):
+ return x
+
+ if self._converter is None:
+ self._set_converter(munits.registry.get_converter(x))
+
+ if self._converter is None:
+ return x
+ try:
+ ret = self._converter.convert(x, self.units, self)
+ except Exception as e:
+ raise munits.ConversionError('Failed to convert value(s) to axis '
+ f'units: {x!r}') from e
+ return ret
+
+ def get_converter(self):
+ """
+ Get the unit converter for axis.
+
+ Returns
+ -------
+ `~matplotlib.units.ConversionInterface` or None
+ """
+ return self._converter
+
+ def set_converter(self, converter):
+ """
+ Set the unit converter for axis.
+
+ Parameters
+ ----------
+ converter : `~matplotlib.units.ConversionInterface`
+ """
+ self._set_converter(converter)
+ self._converter_is_explicit = True
+
+ def _set_converter(self, converter):
+ if self._converter is converter or self._converter == converter:
+ return
+ if self._converter_is_explicit:
+ raise RuntimeError("Axis already has an explicit converter set")
+ elif (
+ self._converter is not None and
+ not isinstance(converter, type(self._converter)) and
+ not isinstance(self._converter, type(converter))
+ ):
+ _api.warn_external(
+ "This axis already has a converter set and "
+ "is updating to a potentially incompatible converter"
+ )
+ self._converter = converter
+
+ def set_units(self, u):
+ """
+ Set the units for axis.
+
+ Parameters
+ ----------
+ u : units tag
+
+ Notes
+ -----
+ The units of any shared axis will also be updated.
+ """
+ if u == self.units:
+ return
+ for axis in self._get_shared_axis():
+ axis.units = u
+ axis._update_axisinfo()
+ axis.callbacks.process('units')
+ axis.stale = True
+
+ def get_units(self):
+ """Return the units for axis."""
+ return self.units
+
+ def set_label_text(self, label, fontdict=None, **kwargs):
+ """
+ Set the text value of the axis label.
+
+ Parameters
+ ----------
+ label : str
+ Text string.
+ fontdict : dict
+ Text properties.
+
+ .. admonition:: Discouraged
+
+ The use of *fontdict* is discouraged. Parameters should be passed as
+ individual keyword arguments or using dictionary-unpacking
+ ``set_label_text(..., **fontdict)``.
+
+ **kwargs
+ Merged into fontdict.
+ """
+ self.isDefault_label = False
+ self.label.set_text(label)
+ if fontdict is not None:
+ self.label.update(fontdict)
+ self.label.update(kwargs)
+ self.stale = True
+ return self.label
+
+ def set_major_formatter(self, formatter):
+ """
+ Set the formatter of the major ticker.
+
+ In addition to a `~matplotlib.ticker.Formatter` instance,
+ this also accepts a ``str`` or function.
+
+ For a ``str`` a `~matplotlib.ticker.StrMethodFormatter` is used.
+ The field used for the value must be labeled ``'x'`` and the field used
+ for the position must be labeled ``'pos'``.
+ See the `~matplotlib.ticker.StrMethodFormatter` documentation for
+ more information.
+
+ For a function, a `~matplotlib.ticker.FuncFormatter` is used.
+ The function must take two inputs (a tick value ``x`` and a
+ position ``pos``), and return a string containing the corresponding
+ tick label.
+ See the `~matplotlib.ticker.FuncFormatter` documentation for
+ more information.
+
+ Parameters
+ ----------
+ formatter : `~matplotlib.ticker.Formatter`, ``str``, or function
+ """
+ self._set_formatter(formatter, self.major)
+
+ def set_minor_formatter(self, formatter):
+ """
+ Set the formatter of the minor ticker.
+
+ In addition to a `~matplotlib.ticker.Formatter` instance,
+ this also accepts a ``str`` or function.
+ See `.Axis.set_major_formatter` for more information.
+
+ Parameters
+ ----------
+ formatter : `~matplotlib.ticker.Formatter`, ``str``, or function
+ """
+ self._set_formatter(formatter, self.minor)
+
+ def _set_formatter(self, formatter, level):
+ if isinstance(formatter, str):
+ formatter = mticker.StrMethodFormatter(formatter)
+ # Don't allow any other TickHelper to avoid easy-to-make errors,
+ # like using a Locator instead of a Formatter.
+ elif (callable(formatter) and
+ not isinstance(formatter, mticker.TickHelper)):
+ formatter = mticker.FuncFormatter(formatter)
+ else:
+ _api.check_isinstance(mticker.Formatter, formatter=formatter)
+
+ if (isinstance(formatter, mticker.FixedFormatter)
+ and len(formatter.seq) > 0
+ and not isinstance(level.locator, mticker.FixedLocator)):
+ _api.warn_external('FixedFormatter should only be used together '
+ 'with FixedLocator')
+
+ if level == self.major:
+ self.isDefault_majfmt = False
+ else:
+ self.isDefault_minfmt = False
+
+ level.formatter = formatter
+ formatter.set_axis(self)
+ self.stale = True
+
+ def set_major_locator(self, locator):
+ """
+ Set the locator of the major ticker.
+
+ Parameters
+ ----------
+ locator : `~matplotlib.ticker.Locator`
+ """
+ _api.check_isinstance(mticker.Locator, locator=locator)
+ self.isDefault_majloc = False
+ self.major.locator = locator
+ if self.major.formatter:
+ self.major.formatter._set_locator(locator)
+ locator.set_axis(self)
+ self.stale = True
+
+ def set_minor_locator(self, locator):
+ """
+ Set the locator of the minor ticker.
+
+ Parameters
+ ----------
+ locator : `~matplotlib.ticker.Locator`
+ """
+ _api.check_isinstance(mticker.Locator, locator=locator)
+ self.isDefault_minloc = False
+ self.minor.locator = locator
+ if self.minor.formatter:
+ self.minor.formatter._set_locator(locator)
+ locator.set_axis(self)
+ self.stale = True
+
+ def set_pickradius(self, pickradius):
+ """
+ Set the depth of the axis used by the picker.
+
+ Parameters
+ ----------
+ pickradius : float
+ The acceptance radius for containment tests.
+ See also `.Axis.contains`.
+ """
+ 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, doc="The acceptance radius for "
+ "containment tests. See also `.Axis.contains`.")
+
+ # Helper for set_ticklabels. Defining it here makes it picklable.
+ @staticmethod
+ def _format_with_dict(tickd, x, pos):
+ return tickd.get(x, "")
+
+ def set_ticklabels(self, labels, *, minor=False, fontdict=None, **kwargs):
+ r"""
+ [*Discouraged*] Set this Axis' tick labels with list of string 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
+ ``Axes.set_[x/y/z]ticks(positions, labels)`` or ``Axis.set_ticks``
+ instead.
+
+ If you are using this method, you should always fix the tick
+ positions before, e.g. by using `.Axis.set_ticks` or by explicitly
+ setting a `~.ticker.FixedLocator`. Otherwise, ticks are free to
+ move and the labels may end up in unexpected positions.
+
+ Parameters
+ ----------
+ labels : sequence of str or of `.Text`\s
+ Texts for labeling each tick location in the sequence set by
+ `.Axis.set_ticks`; the number of labels must match the number of locations.
+ The labels are used as is, via a `.FixedFormatter` (without further
+ formatting).
+
+ minor : bool
+ If True, set minor ticks instead of major ticks.
+
+ fontdict : dict, optional
+
+ .. admonition:: Discouraged
+
+ The use of *fontdict* is discouraged. Parameters should be passed as
+ individual keyword arguments or using dictionary-unpacking
+ ``set_ticklabels(..., **fontdict)``.
+
+ A dictionary controlling the appearance of the ticklabels.
+ The default *fontdict* is::
+
+ {'fontsize': rcParams['axes.titlesize'],
+ 'fontweight': rcParams['axes.titleweight'],
+ 'verticalalignment': 'baseline',
+ 'horizontalalignment': loc}
+
+ **kwargs
+ Text properties.
+
+ .. warning::
+
+ This only sets the properties of the current ticks, which is
+ only sufficient for static plots.
+
+ Ticks are not guaranteed to be persistent. Various operations
+ can create, delete and modify the Tick instances. There is an
+ imminent risk that these settings can get lost if you work on
+ the figure further (including also panning/zooming on a
+ displayed figure).
+
+ Use `.set_tick_params` instead if possible.
+
+ Returns
+ -------
+ list of `.Text`\s
+ For each tick, includes ``tick.label1`` if it is visible, then
+ ``tick.label2`` if it is visible, in that order.
+ """
+ try:
+ labels = [t.get_text() if hasattr(t, 'get_text') else t
+ for t in labels]
+ except TypeError:
+ raise TypeError(f"{labels:=} must be a sequence") from None
+ locator = (self.get_minor_locator() if minor
+ else self.get_major_locator())
+ if not labels:
+ # eg labels=[]:
+ formatter = mticker.NullFormatter()
+ elif isinstance(locator, mticker.FixedLocator):
+ # Passing [] as a list of labels is often used as a way to
+ # remove all tick labels, so only error for > 0 labels
+ if len(locator.locs) != len(labels) and len(labels) != 0:
+ raise ValueError(
+ "The number of FixedLocator locations"
+ f" ({len(locator.locs)}), usually from a call to"
+ " set_ticks, does not match"
+ f" the number of labels ({len(labels)}).")
+ tickd = {loc: lab for loc, lab in zip(locator.locs, labels)}
+ func = functools.partial(self._format_with_dict, tickd)
+ formatter = mticker.FuncFormatter(func)
+ else:
+ _api.warn_external(
+ "set_ticklabels() should only be used with a fixed number of "
+ "ticks, i.e. after set_ticks() or using a FixedLocator.")
+ formatter = mticker.FixedFormatter(labels)
+
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore",
+ message="FixedFormatter should only be used together with FixedLocator")
+ if minor:
+ self.set_minor_formatter(formatter)
+ locs = self.get_minorticklocs()
+ ticks = self.get_minor_ticks(len(locs))
+ else:
+ self.set_major_formatter(formatter)
+ locs = self.get_majorticklocs()
+ ticks = self.get_major_ticks(len(locs))
+
+ ret = []
+ if fontdict is not None:
+ kwargs.update(fontdict)
+ for pos, (loc, tick) in enumerate(zip(locs, ticks)):
+ tick.update_position(loc)
+ tick_label = formatter(loc, pos)
+ # deal with label1
+ tick.label1.set_text(tick_label)
+ tick.label1._internal_update(kwargs)
+ # deal with label2
+ tick.label2.set_text(tick_label)
+ tick.label2._internal_update(kwargs)
+ # only return visible tick labels
+ if tick.label1.get_visible():
+ ret.append(tick.label1)
+ if tick.label2.get_visible():
+ ret.append(tick.label2)
+
+ self.stale = True
+ return ret
+
+ def _set_tick_locations(self, ticks, *, minor=False):
+ # see docstring of set_ticks
+
+ # XXX if the user changes units, the information will be lost here
+ ticks = self.convert_units(ticks)
+ locator = mticker.FixedLocator(ticks) # validate ticks early.
+ if len(ticks):
+ for axis in self._get_shared_axis():
+ # set_view_interval maintains any preexisting inversion.
+ axis.set_view_interval(min(ticks), max(ticks))
+ self.axes.stale = True
+ if minor:
+ self.set_minor_locator(locator)
+ return self.get_minor_ticks(len(ticks))
+ else:
+ self.set_major_locator(locator)
+ return self.get_major_ticks(len(ticks))
+
+ def set_ticks(self, ticks, labels=None, *, minor=False, **kwargs):
+ """
+ Set this Axis' tick locations and optionally tick labels.
+
+ If necessary, the view limits of the Axis are expanded so that all
+ given ticks are visible.
+
+ Parameters
+ ----------
+ ticks : 1D array-like
+ Array of tick locations (either floats or in axis units). The axis
+ `.Locator` is replaced by a `~.ticker.FixedLocator`.
+
+ Pass an empty list (``set_ticks([])``) to remove all ticks.
+
+ Some tick formatters will not label arbitrary tick positions;
+ e.g. log formatters only label decade ticks by default. In
+ such a case you can set a formatter explicitly on the axis
+ using `.Axis.set_major_formatter` or provide formatted
+ *labels* yourself.
+
+ labels : list of str, optional
+ Tick labels for each location in *ticks*; must have the same length as
+ *ticks*. If set, the labels are used as is, via a `.FixedFormatter`.
+ If not set, the labels are generated using the axis tick `.Formatter`.
+
+ minor : bool, default: False
+ If ``False``, set only the major ticks; if ``True``, only the minor ticks.
+
+ **kwargs
+ `.Text` properties for the labels. Using these is only allowed if
+ you pass *labels*. In other cases, please use `~.Axes.tick_params`.
+
+ Notes
+ -----
+ The mandatory expansion of the view limits is an intentional design
+ choice to prevent the surprise of a non-visible tick. If you need
+ other limits, you should set the limits explicitly after setting the
+ ticks.
+ """
+ if labels is None and kwargs:
+ first_key = next(iter(kwargs))
+ raise ValueError(
+ f"Incorrect use of keyword argument {first_key!r}. Keyword arguments "
+ "other than 'minor' modify the text labels and can only be used if "
+ "'labels' are passed as well.")
+ result = self._set_tick_locations(ticks, minor=minor)
+ if labels is not None:
+ self.set_ticklabels(labels, minor=minor, **kwargs)
+ return result
+
+ def _get_tick_boxes_siblings(self, renderer):
+ """
+ Get the bounding boxes for this `.axis` and its siblings
+ as set by `.Figure.align_xlabels` or `.Figure.align_ylabels`.
+
+ By default, it just gets bboxes for *self*.
+ """
+ # Get the Grouper keeping track of x or y label groups for this figure.
+ name = self._get_axis_name()
+ if name not in self.get_figure(root=False)._align_label_groups:
+ return [], []
+ grouper = self.get_figure(root=False)._align_label_groups[name]
+ bboxes = []
+ bboxes2 = []
+ # If we want to align labels from other Axes:
+ for ax in grouper.get_siblings(self.axes):
+ axis = ax._axis_map[name]
+ ticks_to_draw = axis._update_ticks()
+ tlb, tlb2 = axis._get_ticklabel_bboxes(ticks_to_draw, renderer)
+ bboxes.extend(tlb)
+ bboxes2.extend(tlb2)
+ return bboxes, bboxes2
+
+ def _update_label_position(self, renderer):
+ """
+ Update the label position based on the bounding box enclosing
+ all the ticklabels and axis spine.
+ """
+ raise NotImplementedError('Derived must override')
+
+ def _update_offset_text_position(self, bboxes, bboxes2):
+ """
+ Update the offset text position based on the sequence of bounding
+ boxes of all the ticklabels.
+ """
+ raise NotImplementedError('Derived must override')
+
+ def axis_date(self, tz=None):
+ """
+ Set up axis ticks and labels to treat data along this Axis as dates.
+
+ Parameters
+ ----------
+ tz : str or `datetime.tzinfo`, default: :rc:`timezone`
+ The timezone used to create date labels.
+ """
+ # By providing a sample datetime instance with the desired timezone,
+ # the registered converter can be selected, and the "units" attribute,
+ # which is the timezone, can be set.
+ if isinstance(tz, str):
+ import dateutil.tz
+ tz = dateutil.tz.gettz(tz)
+ self.update_units(datetime.datetime(2009, 1, 1, 0, 0, 0, 0, tz))
+
+ def get_tick_space(self):
+ """Return the estimated number of ticks that can fit on the axis."""
+ # Must be overridden in the subclass
+ raise NotImplementedError()
+
+ def _get_ticks_position(self):
+ """
+ Helper for `XAxis.get_ticks_position` and `YAxis.get_ticks_position`.
+
+ Check the visibility of tick1line, label1, tick2line, and label2 on
+ the first major and the first minor ticks, and return
+
+ - 1 if only tick1line and label1 are visible (which corresponds to
+ "bottom" for the x-axis and "left" for the y-axis);
+ - 2 if only tick2line and label2 are visible (which corresponds to
+ "top" for the x-axis and "right" for the y-axis);
+ - "default" if only tick1line, tick2line and label1 are visible;
+ - "unknown" otherwise.
+ """
+ major = self.majorTicks[0]
+ minor = self.minorTicks[0]
+ if all(tick.tick1line.get_visible()
+ and not tick.tick2line.get_visible()
+ and tick.label1.get_visible()
+ and not tick.label2.get_visible()
+ for tick in [major, minor]):
+ return 1
+ elif all(tick.tick2line.get_visible()
+ and not tick.tick1line.get_visible()
+ and tick.label2.get_visible()
+ and not tick.label1.get_visible()
+ for tick in [major, minor]):
+ return 2
+ elif all(tick.tick1line.get_visible()
+ and tick.tick2line.get_visible()
+ and tick.label1.get_visible()
+ and not tick.label2.get_visible()
+ for tick in [major, minor]):
+ return "default"
+ else:
+ return "unknown"
+
+ def get_label_position(self):
+ """
+ Return the label position (top or bottom)
+ """
+ return self.label_position
+
+ def set_label_position(self, position):
+ """
+ Set the label position (top or bottom)
+
+ Parameters
+ ----------
+ position : {'top', 'bottom'}
+ """
+ raise NotImplementedError()
+
+ def get_minpos(self):
+ raise NotImplementedError()
+
+
+def _make_getset_interval(method_name, lim_name, attr_name):
+ """
+ Helper to generate ``get_{data,view}_interval`` and
+ ``set_{data,view}_interval`` implementations.
+ """
+
+ def getter(self):
+ # docstring inherited.
+ return getattr(getattr(self.axes, lim_name), attr_name)
+
+ def setter(self, vmin, vmax, ignore=False):
+ # docstring inherited.
+ if ignore:
+ setattr(getattr(self.axes, lim_name), attr_name, (vmin, vmax))
+ else:
+ oldmin, oldmax = getter(self)
+ if oldmin < oldmax:
+ setter(self, min(vmin, vmax, oldmin), max(vmin, vmax, oldmax),
+ ignore=True)
+ else:
+ setter(self, max(vmin, vmax, oldmin), min(vmin, vmax, oldmax),
+ ignore=True)
+ self.stale = True
+
+ getter.__name__ = f"get_{method_name}_interval"
+ setter.__name__ = f"set_{method_name}_interval"
+
+ return getter, setter
+
+
+class XAxis(Axis):
+ __name__ = 'xaxis'
+ axis_name = 'x' #: Read-only name identifying the axis.
+ _tick_class = XTick
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self._init()
+
+ def _init(self):
+ """
+ Initialize the label and offsetText instance values and
+ `label_position` / `offset_text_position`.
+ """
+ # x in axes coords, y in display coords (to be updated at draw time by
+ # _update_label_positions and _update_offset_text_position).
+ self.label.set(
+ x=0.5, y=0,
+ verticalalignment='top', horizontalalignment='center',
+ transform=mtransforms.blended_transform_factory(
+ self.axes.transAxes, mtransforms.IdentityTransform()),
+ )
+ self.label_position = 'bottom'
+
+ if mpl.rcParams['xtick.labelcolor'] == 'inherit':
+ tick_color = mpl.rcParams['xtick.color']
+ else:
+ tick_color = mpl.rcParams['xtick.labelcolor']
+
+ self.offsetText.set(
+ x=1, y=0,
+ verticalalignment='top', horizontalalignment='right',
+ transform=mtransforms.blended_transform_factory(
+ self.axes.transAxes, mtransforms.IdentityTransform()),
+ fontsize=mpl.rcParams['xtick.labelsize'],
+ color=tick_color
+ )
+ self.offset_text_position = 'bottom'
+
+ def contains(self, mouseevent):
+ """Test whether the mouse event occurred in the x-axis."""
+ if self._different_canvas(mouseevent):
+ return False, {}
+ x, y = mouseevent.x, mouseevent.y
+ try:
+ trans = self.axes.transAxes.inverted()
+ xaxes, yaxes = trans.transform((x, y))
+ except ValueError:
+ return False, {}
+ (l, b), (r, t) = self.axes.transAxes.transform([(0, 0), (1, 1)])
+ inaxis = 0 <= xaxes <= 1 and (
+ b - self._pickradius < y < b or
+ t < y < t + self._pickradius)
+ return inaxis, {}
+
+ def set_label_position(self, position):
+ """
+ Set the label position (top or bottom)
+
+ Parameters
+ ----------
+ position : {'top', 'bottom'}
+ """
+ self.label.set_verticalalignment(_api.check_getitem({
+ 'top': 'baseline', 'bottom': 'top',
+ }, position=position))
+ self.label_position = position
+ self.stale = True
+
+ def _update_label_position(self, renderer):
+ """
+ Update the label position based on the bounding box enclosing
+ all the ticklabels and axis spine
+ """
+ if not self._autolabelpos:
+ return
+
+ # get bounding boxes for this axis and any siblings
+ # that have been set by `fig.align_xlabels()`
+ bboxes, bboxes2 = self._get_tick_boxes_siblings(renderer=renderer)
+ x, y = self.label.get_position()
+
+ if self.label_position == 'bottom':
+ # Union with extents of the bottom spine if present, of the axes otherwise.
+ bbox = mtransforms.Bbox.union([
+ *bboxes, self.axes.spines.get("bottom", self.axes).get_window_extent()])
+ self.label.set_position(
+ (x, bbox.y0 - self.labelpad * self.get_figure(root=True).dpi / 72))
+ else:
+ # Union with extents of the top spine if present, of the axes otherwise.
+ bbox = mtransforms.Bbox.union([
+ *bboxes2, self.axes.spines.get("top", self.axes).get_window_extent()])
+ self.label.set_position(
+ (x, bbox.y1 + self.labelpad * self.get_figure(root=True).dpi / 72))
+
+ def _update_offset_text_position(self, bboxes, bboxes2):
+ """
+ Update the offset_text position based on the sequence of bounding
+ boxes of all the ticklabels
+ """
+ x, y = self.offsetText.get_position()
+ if not hasattr(self, '_tick_position'):
+ self._tick_position = 'bottom'
+ if self._tick_position == 'bottom':
+ if not len(bboxes):
+ bottom = self.axes.bbox.ymin
+ else:
+ bbox = mtransforms.Bbox.union(bboxes)
+ bottom = bbox.y0
+ y = bottom - self.OFFSETTEXTPAD * self.get_figure(root=True).dpi / 72
+ else:
+ if not len(bboxes2):
+ top = self.axes.bbox.ymax
+ else:
+ bbox = mtransforms.Bbox.union(bboxes2)
+ top = bbox.y1
+ y = top + self.OFFSETTEXTPAD * self.get_figure(root=True).dpi / 72
+ self.offsetText.set_position((x, y))
+
+ def set_ticks_position(self, position):
+ """
+ Set the ticks position.
+
+ Parameters
+ ----------
+ position : {'top', 'bottom', 'both', 'default', 'none'}
+ 'both' sets the ticks to appear on both positions, but does not
+ change the tick labels. 'default' resets the tick positions to
+ the default: ticks on both positions, labels at bottom. 'none'
+ can be used if you don't want any ticks. 'none' and 'both'
+ affect only the ticks, not the labels.
+ """
+ if position == 'top':
+ self.set_tick_params(which='both', top=True, labeltop=True,
+ bottom=False, labelbottom=False)
+ self._tick_position = 'top'
+ self.offsetText.set_verticalalignment('bottom')
+ elif position == 'bottom':
+ self.set_tick_params(which='both', top=False, labeltop=False,
+ bottom=True, labelbottom=True)
+ self._tick_position = 'bottom'
+ self.offsetText.set_verticalalignment('top')
+ elif position == 'both':
+ self.set_tick_params(which='both', top=True,
+ bottom=True)
+ elif position == 'none':
+ self.set_tick_params(which='both', top=False,
+ bottom=False)
+ elif position == 'default':
+ self.set_tick_params(which='both', top=True, labeltop=False,
+ bottom=True, labelbottom=True)
+ self._tick_position = 'bottom'
+ self.offsetText.set_verticalalignment('top')
+ else:
+ _api.check_in_list(['top', 'bottom', 'both', 'default', 'none'],
+ position=position)
+ self.stale = True
+
+ def tick_top(self):
+ """
+ Move ticks and ticklabels (if present) to the top of the Axes.
+ """
+ label = True
+ if 'label1On' in self._major_tick_kw:
+ label = (self._major_tick_kw['label1On']
+ or self._major_tick_kw['label2On'])
+ self.set_ticks_position('top')
+ # If labels were turned off before this was called, leave them off.
+ self.set_tick_params(which='both', labeltop=label)
+
+ def tick_bottom(self):
+ """
+ Move ticks and ticklabels (if present) to the bottom of the Axes.
+ """
+ label = True
+ if 'label1On' in self._major_tick_kw:
+ label = (self._major_tick_kw['label1On']
+ or self._major_tick_kw['label2On'])
+ self.set_ticks_position('bottom')
+ # If labels were turned off before this was called, leave them off.
+ self.set_tick_params(which='both', labelbottom=label)
+
+ def get_ticks_position(self):
+ """
+ Return the ticks position ("top", "bottom", "default", or "unknown").
+ """
+ return {1: "bottom", 2: "top",
+ "default": "default", "unknown": "unknown"}[
+ self._get_ticks_position()]
+
+ get_view_interval, set_view_interval = _make_getset_interval(
+ "view", "viewLim", "intervalx")
+ get_data_interval, set_data_interval = _make_getset_interval(
+ "data", "dataLim", "intervalx")
+
+ def get_minpos(self):
+ return self.axes.dataLim.minposx
+
+ def set_default_intervals(self):
+ # docstring inherited
+ # only change view if dataLim has not changed and user has
+ # not changed the view:
+ if (not self.axes.dataLim.mutatedx() and
+ not self.axes.viewLim.mutatedx()):
+ if self._converter is not None:
+ info = self._converter.axisinfo(self.units, self)
+ if info.default_limits is not None:
+ xmin, xmax = self.convert_units(info.default_limits)
+ self.axes.viewLim.intervalx = xmin, xmax
+ self.stale = True
+
+ def get_tick_space(self):
+ ends = mtransforms.Bbox.unit().transformed(
+ self.axes.transAxes - self.get_figure(root=False).dpi_scale_trans)
+ length = ends.width * 72
+ # There is a heuristic here that the aspect ratio of tick text
+ # is no more than 3:1
+ size = self._get_tick_label_size('x') * 3
+ if size > 0:
+ return int(np.floor(length / size))
+ else:
+ return 2**31 - 1
+
+
+class YAxis(Axis):
+ __name__ = 'yaxis'
+ axis_name = 'y' #: Read-only name identifying the axis.
+ _tick_class = YTick
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self._init()
+
+ def _init(self):
+ """
+ Initialize the label and offsetText instance values and
+ `label_position` / `offset_text_position`.
+ """
+ # x in display coords, y in axes coords (to be updated at draw time by
+ # _update_label_positions and _update_offset_text_position).
+ self.label.set(
+ x=0, y=0.5,
+ verticalalignment='bottom', horizontalalignment='center',
+ rotation='vertical', rotation_mode='anchor',
+ transform=mtransforms.blended_transform_factory(
+ mtransforms.IdentityTransform(), self.axes.transAxes),
+ )
+ self.label_position = 'left'
+
+ if mpl.rcParams['ytick.labelcolor'] == 'inherit':
+ tick_color = mpl.rcParams['ytick.color']
+ else:
+ tick_color = mpl.rcParams['ytick.labelcolor']
+
+ # x in axes coords, y in display coords(!).
+ self.offsetText.set(
+ x=0, y=0.5,
+ verticalalignment='baseline', horizontalalignment='left',
+ transform=mtransforms.blended_transform_factory(
+ self.axes.transAxes, mtransforms.IdentityTransform()),
+ fontsize=mpl.rcParams['ytick.labelsize'],
+ color=tick_color
+ )
+ self.offset_text_position = 'left'
+
+ def contains(self, mouseevent):
+ # docstring inherited
+ if self._different_canvas(mouseevent):
+ return False, {}
+ x, y = mouseevent.x, mouseevent.y
+ try:
+ trans = self.axes.transAxes.inverted()
+ xaxes, yaxes = trans.transform((x, y))
+ except ValueError:
+ return False, {}
+ (l, b), (r, t) = self.axes.transAxes.transform([(0, 0), (1, 1)])
+ inaxis = 0 <= yaxes <= 1 and (
+ l - self._pickradius < x < l or
+ r < x < r + self._pickradius)
+ return inaxis, {}
+
+ def set_label_position(self, position):
+ """
+ Set the label position (left or right)
+
+ Parameters
+ ----------
+ position : {'left', 'right'}
+ """
+ self.label.set_rotation_mode('anchor')
+ self.label.set_verticalalignment(_api.check_getitem({
+ 'left': 'bottom', 'right': 'top',
+ }, position=position))
+ self.label_position = position
+ self.stale = True
+
+ def _update_label_position(self, renderer):
+ """
+ Update the label position based on the bounding box enclosing
+ all the ticklabels and axis spine
+ """
+ if not self._autolabelpos:
+ return
+
+ # get bounding boxes for this axis and any siblings
+ # that have been set by `fig.align_ylabels()`
+ bboxes, bboxes2 = self._get_tick_boxes_siblings(renderer=renderer)
+ x, y = self.label.get_position()
+
+ if self.label_position == 'left':
+ # Union with extents of the left spine if present, of the axes otherwise.
+ bbox = mtransforms.Bbox.union([
+ *bboxes, self.axes.spines.get("left", self.axes).get_window_extent()])
+ self.label.set_position(
+ (bbox.x0 - self.labelpad * self.get_figure(root=True).dpi / 72, y))
+ else:
+ # Union with extents of the right spine if present, of the axes otherwise.
+ bbox = mtransforms.Bbox.union([
+ *bboxes2, self.axes.spines.get("right", self.axes).get_window_extent()])
+ self.label.set_position(
+ (bbox.x1 + self.labelpad * self.get_figure(root=True).dpi / 72, y))
+
+ def _update_offset_text_position(self, bboxes, bboxes2):
+ """
+ Update the offset_text position based on the sequence of bounding
+ boxes of all the ticklabels
+ """
+ x, _ = self.offsetText.get_position()
+ if 'outline' in self.axes.spines:
+ # Special case for colorbars:
+ bbox = self.axes.spines['outline'].get_window_extent()
+ else:
+ bbox = self.axes.bbox
+ top = bbox.ymax
+ self.offsetText.set_position(
+ (x, top + self.OFFSETTEXTPAD * self.get_figure(root=True).dpi / 72)
+ )
+
+ def set_offset_position(self, position):
+ """
+ Parameters
+ ----------
+ position : {'left', 'right'}
+ """
+ x, y = self.offsetText.get_position()
+ x = _api.check_getitem({'left': 0, 'right': 1}, position=position)
+
+ self.offsetText.set_ha(position)
+ self.offsetText.set_position((x, y))
+ self.stale = True
+
+ def set_ticks_position(self, position):
+ """
+ Set the ticks position.
+
+ Parameters
+ ----------
+ position : {'left', 'right', 'both', 'default', 'none'}
+ 'both' sets the ticks to appear on both positions, but does not
+ change the tick labels. 'default' resets the tick positions to
+ the default: ticks on both positions, labels at left. 'none'
+ can be used if you don't want any ticks. 'none' and 'both'
+ affect only the ticks, not the labels.
+ """
+ if position == 'right':
+ self.set_tick_params(which='both', right=True, labelright=True,
+ left=False, labelleft=False)
+ self.set_offset_position(position)
+ elif position == 'left':
+ self.set_tick_params(which='both', right=False, labelright=False,
+ left=True, labelleft=True)
+ self.set_offset_position(position)
+ elif position == 'both':
+ self.set_tick_params(which='both', right=True,
+ left=True)
+ elif position == 'none':
+ self.set_tick_params(which='both', right=False,
+ left=False)
+ elif position == 'default':
+ self.set_tick_params(which='both', right=True, labelright=False,
+ left=True, labelleft=True)
+ else:
+ _api.check_in_list(['left', 'right', 'both', 'default', 'none'],
+ position=position)
+ self.stale = True
+
+ def tick_right(self):
+ """
+ Move ticks and ticklabels (if present) to the right of the Axes.
+ """
+ label = True
+ if 'label1On' in self._major_tick_kw:
+ label = (self._major_tick_kw['label1On']
+ or self._major_tick_kw['label2On'])
+ self.set_ticks_position('right')
+ # if labels were turned off before this was called
+ # leave them off
+ self.set_tick_params(which='both', labelright=label)
+
+ def tick_left(self):
+ """
+ Move ticks and ticklabels (if present) to the left of the Axes.
+ """
+ label = True
+ if 'label1On' in self._major_tick_kw:
+ label = (self._major_tick_kw['label1On']
+ or self._major_tick_kw['label2On'])
+ self.set_ticks_position('left')
+ # if labels were turned off before this was called
+ # leave them off
+ self.set_tick_params(which='both', labelleft=label)
+
+ def get_ticks_position(self):
+ """
+ Return the ticks position ("left", "right", "default", or "unknown").
+ """
+ return {1: "left", 2: "right",
+ "default": "default", "unknown": "unknown"}[
+ self._get_ticks_position()]
+
+ get_view_interval, set_view_interval = _make_getset_interval(
+ "view", "viewLim", "intervaly")
+ get_data_interval, set_data_interval = _make_getset_interval(
+ "data", "dataLim", "intervaly")
+
+ def get_minpos(self):
+ return self.axes.dataLim.minposy
+
+ def set_default_intervals(self):
+ # docstring inherited
+ # only change view if dataLim has not changed and user has
+ # not changed the view:
+ if (not self.axes.dataLim.mutatedy() and
+ not self.axes.viewLim.mutatedy()):
+ if self._converter is not None:
+ info = self._converter.axisinfo(self.units, self)
+ if info.default_limits is not None:
+ ymin, ymax = self.convert_units(info.default_limits)
+ self.axes.viewLim.intervaly = ymin, ymax
+ self.stale = True
+
+ def get_tick_space(self):
+ ends = mtransforms.Bbox.unit().transformed(
+ self.axes.transAxes - self.get_figure(root=False).dpi_scale_trans)
+ length = ends.height * 72
+ # Having a spacing of at least 2 just looks good.
+ size = self._get_tick_label_size('y') * 2
+ if size > 0:
+ return int(np.floor(length / size))
+ else:
+ return 2**31 - 1
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/axis.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/axis.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..f2c5b1fc586d5a33237ace5ec264b6f6fde49080
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/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/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/backend_bases.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/backend_bases.py
new file mode 100644
index 0000000000000000000000000000000000000000..e9f06fd94618fc3932ae65a406579292d18b1514
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/backend_bases.py
@@ -0,0 +1,3585 @@
+"""
+Abstract base classes define the primitives that renderers and
+graphics contexts must implement to serve as a Matplotlib backend.
+
+`RendererBase`
+ An abstract base class to handle drawing/rendering operations.
+
+`FigureCanvasBase`
+ The abstraction layer that separates the `.Figure` from the backend
+ specific details like a user interface drawing area.
+
+`GraphicsContextBase`
+ An abstract base class that provides color, line styles, etc.
+
+`Event`
+ The base class for all of the Matplotlib event handling. Derived classes
+ such as `KeyEvent` and `MouseEvent` store the meta data like keys and
+ buttons pressed, x and y locations in pixel and `~.axes.Axes` coordinates.
+
+`ShowBase`
+ The base class for the ``Show`` class of each interactive backend; the
+ 'show' callable is then set to ``Show.__call__``.
+
+`ToolContainerBase`
+ The base class for the Toolbar class of each interactive backend.
+"""
+
+from collections import namedtuple
+from contextlib import ExitStack, contextmanager, nullcontext
+from enum import Enum, IntEnum
+import functools
+import importlib
+import inspect
+import io
+import itertools
+import logging
+import os
+import pathlib
+import signal
+import socket
+import sys
+import time
+import weakref
+from weakref import WeakKeyDictionary
+
+import numpy as np
+
+import matplotlib as mpl
+from matplotlib import (
+ _api, backend_tools as tools, cbook, colors, _docstring, text,
+ _tight_bbox, transforms, widgets, is_interactive, rcParams)
+from matplotlib._pylab_helpers import Gcf
+from matplotlib.backend_managers import ToolManager
+from matplotlib.cbook import _setattr_cm
+from matplotlib.layout_engine import ConstrainedLayoutEngine
+from matplotlib.path import Path
+from matplotlib.texmanager import TexManager
+from matplotlib.transforms import Affine2D
+from matplotlib._enums import JoinStyle, CapStyle
+
+
+_log = logging.getLogger(__name__)
+_default_filetypes = {
+ 'eps': 'Encapsulated Postscript',
+ 'jpg': 'Joint Photographic Experts Group',
+ 'jpeg': 'Joint Photographic Experts Group',
+ 'pdf': 'Portable Document Format',
+ 'pgf': 'PGF code for LaTeX',
+ 'png': 'Portable Network Graphics',
+ 'ps': 'Postscript',
+ 'raw': 'Raw RGBA bitmap',
+ 'rgba': 'Raw RGBA bitmap',
+ 'svg': 'Scalable Vector Graphics',
+ 'svgz': 'Scalable Vector Graphics',
+ 'tif': 'Tagged Image File Format',
+ 'tiff': 'Tagged Image File Format',
+ 'webp': 'WebP Image Format',
+}
+_default_backends = {
+ 'eps': 'matplotlib.backends.backend_ps',
+ 'jpg': 'matplotlib.backends.backend_agg',
+ 'jpeg': 'matplotlib.backends.backend_agg',
+ 'pdf': 'matplotlib.backends.backend_pdf',
+ 'pgf': 'matplotlib.backends.backend_pgf',
+ 'png': 'matplotlib.backends.backend_agg',
+ 'ps': 'matplotlib.backends.backend_ps',
+ 'raw': 'matplotlib.backends.backend_agg',
+ 'rgba': 'matplotlib.backends.backend_agg',
+ 'svg': 'matplotlib.backends.backend_svg',
+ 'svgz': 'matplotlib.backends.backend_svg',
+ 'tif': 'matplotlib.backends.backend_agg',
+ 'tiff': 'matplotlib.backends.backend_agg',
+ 'webp': 'matplotlib.backends.backend_agg',
+}
+
+
+def register_backend(format, backend, description=None):
+ """
+ Register a backend for saving to a given file format.
+
+ Parameters
+ ----------
+ format : str
+ File extension
+ backend : module string or canvas class
+ Backend for handling file output
+ description : str, default: ""
+ Description of the file type.
+ """
+ if description is None:
+ description = ''
+ _default_backends[format] = backend
+ _default_filetypes[format] = description
+
+
+def get_registered_canvas_class(format):
+ """
+ Return the registered default canvas for given file format.
+ Handles deferred import of required backend.
+ """
+ if format not in _default_backends:
+ return None
+ backend_class = _default_backends[format]
+ if isinstance(backend_class, str):
+ backend_class = importlib.import_module(backend_class).FigureCanvas
+ _default_backends[format] = backend_class
+ return backend_class
+
+
+class RendererBase:
+ """
+ An abstract base class to handle drawing/rendering operations.
+
+ The following methods must be implemented in the backend for full
+ functionality (though just implementing `draw_path` alone would give a
+ highly capable backend):
+
+ * `draw_path`
+ * `draw_image`
+ * `draw_gouraud_triangles`
+
+ The following methods *should* be implemented in the backend for
+ optimization reasons:
+
+ * `draw_text`
+ * `draw_markers`
+ * `draw_path_collection`
+ * `draw_quad_mesh`
+ """
+ def __init__(self):
+ super().__init__()
+ self._texmanager = None
+ self._text2path = text.TextToPath()
+ self._raster_depth = 0
+ self._rasterizing = False
+
+ def open_group(self, s, gid=None):
+ """
+ Open a grouping element with label *s* and *gid* (if set) as id.
+
+ Only used by the SVG renderer.
+ """
+
+ def close_group(self, s):
+ """
+ Close a grouping element with label *s*.
+
+ Only used by the SVG renderer.
+ """
+
+ def draw_path(self, gc, path, transform, rgbFace=None):
+ """Draw a `~.path.Path` instance using the given affine transform."""
+ raise NotImplementedError
+
+ def draw_markers(self, gc, marker_path, marker_trans, path,
+ trans, rgbFace=None):
+ """
+ Draw a marker at each of *path*'s vertices (excluding control points).
+
+ The base (fallback) implementation makes multiple calls to `draw_path`.
+ Backends may want to override this method in order to draw the marker
+ only once and reuse it multiple times.
+
+ Parameters
+ ----------
+ gc : `.GraphicsContextBase`
+ The graphics context.
+ marker_path : `~matplotlib.path.Path`
+ The path for the marker.
+ marker_trans : `~matplotlib.transforms.Transform`
+ An affine transform applied to the marker.
+ path : `~matplotlib.path.Path`
+ The locations to draw the markers.
+ trans : `~matplotlib.transforms.Transform`
+ An affine transform applied to the path.
+ rgbFace : :mpltype:`color`, optional
+ """
+ for vertices, codes in path.iter_segments(trans, simplify=False):
+ if len(vertices):
+ x, y = vertices[-2:]
+ self.draw_path(gc, marker_path,
+ marker_trans +
+ transforms.Affine2D().translate(x, y),
+ rgbFace)
+
+ def draw_path_collection(self, gc, master_transform, paths, all_transforms,
+ offsets, offset_trans, facecolors, edgecolors,
+ linewidths, linestyles, antialiaseds, urls,
+ offset_position):
+ """
+ Draw a collection of *paths*.
+
+ Each path is first transformed by the corresponding entry
+ in *all_transforms* (a list of (3, 3) matrices) and then by
+ *master_transform*. They are then translated by the corresponding
+ entry in *offsets*, which has been first transformed by *offset_trans*.
+
+ *facecolors*, *edgecolors*, *linewidths*, *linestyles*, and
+ *antialiased* are lists that set the corresponding properties.
+
+ *offset_position* is unused now, but the argument is kept for
+ backwards compatibility.
+
+ The base (fallback) implementation makes multiple calls to `draw_path`.
+ Backends may want to override this in order to render each set of
+ path data only once, and then reference that path multiple times with
+ the different offsets, colors, styles etc. The generator methods
+ `_iter_collection_raw_paths` and `_iter_collection` are provided to
+ help with (and standardize) the implementation across backends. It
+ is highly recommended to use those generators, so that changes to the
+ behavior of `draw_path_collection` can be made globally.
+ """
+ path_ids = self._iter_collection_raw_paths(master_transform,
+ paths, all_transforms)
+
+ for xo, yo, path_id, gc0, rgbFace in self._iter_collection(
+ gc, list(path_ids), offsets, offset_trans,
+ facecolors, edgecolors, linewidths, linestyles,
+ antialiaseds, urls, offset_position):
+ path, transform = path_id
+ # Only apply another translation if we have an offset, else we
+ # reuse the initial transform.
+ if xo != 0 or yo != 0:
+ # The transformation can be used by multiple paths. Since
+ # translate is a inplace operation, we need to copy the
+ # transformation by .frozen() before applying the translation.
+ transform = transform.frozen()
+ transform.translate(xo, yo)
+ self.draw_path(gc0, path, transform, rgbFace)
+
+ def draw_quad_mesh(self, gc, master_transform, meshWidth, meshHeight,
+ coordinates, offsets, offsetTrans, facecolors,
+ antialiased, edgecolors):
+ """
+ Draw a quadmesh.
+
+ The base (fallback) implementation converts the quadmesh to paths and
+ then calls `draw_path_collection`.
+ """
+
+ from matplotlib.collections import QuadMesh
+ paths = QuadMesh._convert_mesh_to_paths(coordinates)
+
+ if edgecolors is None:
+ edgecolors = facecolors
+ linewidths = np.array([gc.get_linewidth()], float)
+
+ return self.draw_path_collection(
+ gc, master_transform, paths, [], offsets, offsetTrans, facecolors,
+ edgecolors, linewidths, [], [antialiased], [None], 'screen')
+
+ def draw_gouraud_triangles(self, gc, triangles_array, colors_array,
+ transform):
+ """
+ Draw a series of Gouraud triangles.
+
+ Parameters
+ ----------
+ gc : `.GraphicsContextBase`
+ The graphics context.
+ triangles_array : (N, 3, 2) array-like
+ Array of *N* (x, y) points for the triangles.
+ colors_array : (N, 3, 4) array-like
+ Array of *N* RGBA colors for each point of the triangles.
+ transform : `~matplotlib.transforms.Transform`
+ An affine transform to apply to the points.
+ """
+ raise NotImplementedError
+
+ def _iter_collection_raw_paths(self, master_transform, paths,
+ all_transforms):
+ """
+ Helper method (along with `_iter_collection`) to implement
+ `draw_path_collection` in a memory-efficient manner.
+
+ This method yields all of the base path/transform combinations, given a
+ master transform, a list of paths and list of transforms.
+
+ The arguments should be exactly what is passed in to
+ `draw_path_collection`.
+
+ The backend should take each yielded path and transform and create an
+ object that can be referenced (reused) later.
+ """
+ Npaths = len(paths)
+ Ntransforms = len(all_transforms)
+ N = max(Npaths, Ntransforms)
+
+ if Npaths == 0:
+ return
+
+ transform = transforms.IdentityTransform()
+ for i in range(N):
+ path = paths[i % Npaths]
+ if Ntransforms:
+ transform = Affine2D(all_transforms[i % Ntransforms])
+ yield path, transform + master_transform
+
+ def _iter_collection_uses_per_path(self, paths, all_transforms,
+ offsets, facecolors, edgecolors):
+ """
+ Compute how many times each raw path object returned by
+ `_iter_collection_raw_paths` would be used when calling
+ `_iter_collection`. This is intended for the backend to decide
+ on the tradeoff between using the paths in-line and storing
+ them once and reusing. Rounds up in case the number of uses
+ is not the same for every path.
+ """
+ Npaths = len(paths)
+ if Npaths == 0 or len(facecolors) == len(edgecolors) == 0:
+ return 0
+ Npath_ids = max(Npaths, len(all_transforms))
+ N = max(Npath_ids, len(offsets))
+ return (N + Npath_ids - 1) // Npath_ids
+
+ def _iter_collection(self, gc, path_ids, offsets, offset_trans, facecolors,
+ edgecolors, linewidths, linestyles,
+ antialiaseds, urls, offset_position):
+ """
+ Helper method (along with `_iter_collection_raw_paths`) to implement
+ `draw_path_collection` in a memory-efficient manner.
+
+ This method yields all of the path, offset and graphics context
+ combinations to draw the path collection. The caller should already
+ have looped over the results of `_iter_collection_raw_paths` to draw
+ this collection.
+
+ The arguments should be the same as that passed into
+ `draw_path_collection`, with the exception of *path_ids*, which is a
+ list of arbitrary objects that the backend will use to reference one of
+ the paths created in the `_iter_collection_raw_paths` stage.
+
+ Each yielded result is of the form::
+
+ xo, yo, path_id, gc, rgbFace
+
+ where *xo*, *yo* is an offset; *path_id* is one of the elements of
+ *path_ids*; *gc* is a graphics context and *rgbFace* is a color to
+ use for filling the path.
+ """
+ Npaths = len(path_ids)
+ Noffsets = len(offsets)
+ N = max(Npaths, Noffsets)
+ Nfacecolors = len(facecolors)
+ Nedgecolors = len(edgecolors)
+ Nlinewidths = len(linewidths)
+ Nlinestyles = len(linestyles)
+ Nurls = len(urls)
+
+ if (Nfacecolors == 0 and Nedgecolors == 0) or Npaths == 0:
+ return
+
+ gc0 = self.new_gc()
+ gc0.copy_properties(gc)
+
+ def cycle_or_default(seq, default=None):
+ # Cycle over *seq* if it is not empty; else always yield *default*.
+ return (itertools.cycle(seq) if len(seq)
+ else itertools.repeat(default))
+
+ pathids = cycle_or_default(path_ids)
+ toffsets = cycle_or_default(offset_trans.transform(offsets), (0, 0))
+ fcs = cycle_or_default(facecolors)
+ ecs = cycle_or_default(edgecolors)
+ lws = cycle_or_default(linewidths)
+ lss = cycle_or_default(linestyles)
+ aas = cycle_or_default(antialiaseds)
+ urls = cycle_or_default(urls)
+
+ if Nedgecolors == 0:
+ gc0.set_linewidth(0.0)
+
+ for pathid, (xo, yo), fc, ec, lw, ls, aa, url in itertools.islice(
+ zip(pathids, toffsets, fcs, ecs, lws, lss, aas, urls), N):
+ if not (np.isfinite(xo) and np.isfinite(yo)):
+ continue
+ if Nedgecolors:
+ if Nlinewidths:
+ gc0.set_linewidth(lw)
+ if Nlinestyles:
+ gc0.set_dashes(*ls)
+ if len(ec) == 4 and ec[3] == 0.0:
+ gc0.set_linewidth(0)
+ else:
+ gc0.set_foreground(ec)
+ if fc is not None and len(fc) == 4 and fc[3] == 0:
+ fc = None
+ gc0.set_antialiased(aa)
+ if Nurls:
+ gc0.set_url(url)
+ yield xo, yo, pathid, gc0, fc
+ gc0.restore()
+
+ def get_image_magnification(self):
+ """
+ Get the factor by which to magnify images passed to `draw_image`.
+ Allows a backend to have images at a different resolution to other
+ artists.
+ """
+ return 1.0
+
+ def draw_image(self, gc, x, y, im, transform=None):
+ """
+ Draw an RGBA image.
+
+ Parameters
+ ----------
+ gc : `.GraphicsContextBase`
+ A graphics context with clipping information.
+
+ x : float
+ The distance in physical units (i.e., dots or pixels) from the left
+ hand side of the canvas.
+
+ y : float
+ The distance in physical units (i.e., dots or pixels) from the
+ bottom side of the canvas.
+
+ im : (N, M, 4) array of `numpy.uint8`
+ An array of RGBA pixels.
+
+ transform : `~matplotlib.transforms.Affine2DBase`
+ If and only if the concrete backend is written such that
+ `option_scale_image` returns ``True``, an affine transformation
+ (i.e., an `.Affine2DBase`) *may* be passed to `draw_image`. The
+ translation vector of the transformation is given in physical units
+ (i.e., dots or pixels). Note that the transformation does not
+ override *x* and *y*, and has to be applied *before* translating
+ the result by *x* and *y* (this can be accomplished by adding *x*
+ and *y* to the translation vector defined by *transform*).
+ """
+ raise NotImplementedError
+
+ def option_image_nocomposite(self):
+ """
+ Return whether image composition by Matplotlib should be skipped.
+
+ Raster backends should usually return False (letting the C-level
+ rasterizer take care of image composition); vector backends should
+ usually return ``not rcParams["image.composite_image"]``.
+ """
+ return False
+
+ def option_scale_image(self):
+ """
+ Return whether arbitrary affine transformations in `draw_image` are
+ supported (True for most vector backends).
+ """
+ return False
+
+ def draw_tex(self, gc, x, y, s, prop, angle, *, mtext=None):
+ """
+ Draw a TeX instance.
+
+ Parameters
+ ----------
+ gc : `.GraphicsContextBase`
+ The graphics context.
+ x : float
+ The x location of the text in display coords.
+ y : float
+ The y location of the text baseline in display coords.
+ s : str
+ The TeX text string.
+ prop : `~matplotlib.font_manager.FontProperties`
+ The font properties.
+ angle : float
+ The rotation angle in degrees anti-clockwise.
+ mtext : `~matplotlib.text.Text`
+ The original text object to be rendered.
+ """
+ self._draw_text_as_path(gc, x, y, s, prop, angle, ismath="TeX")
+
+ def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
+ """
+ Draw a text instance.
+
+ Parameters
+ ----------
+ gc : `.GraphicsContextBase`
+ The graphics context.
+ x : float
+ The x location of the text in display coords.
+ y : float
+ The y location of the text baseline in display coords.
+ s : str
+ The text string.
+ prop : `~matplotlib.font_manager.FontProperties`
+ The font properties.
+ angle : float
+ The rotation angle in degrees anti-clockwise.
+ ismath : bool or "TeX"
+ If True, use mathtext parser.
+ mtext : `~matplotlib.text.Text`
+ The original text object to be rendered.
+
+ Notes
+ -----
+ **Notes for backend implementers:**
+
+ `.RendererBase.draw_text` also supports passing "TeX" to the *ismath*
+ parameter to use TeX rendering, but this is not required for actual
+ rendering backends, and indeed many builtin backends do not support
+ this. Rather, TeX rendering is provided by `~.RendererBase.draw_tex`.
+ """
+ self._draw_text_as_path(gc, x, y, s, prop, angle, ismath)
+
+ def _draw_text_as_path(self, gc, x, y, s, prop, angle, ismath):
+ """
+ Draw the text by converting them to paths using `.TextToPath`.
+
+ This private helper supports the same parameters as
+ `~.RendererBase.draw_text`; setting *ismath* to "TeX" triggers TeX
+ rendering.
+ """
+ text2path = self._text2path
+ fontsize = self.points_to_pixels(prop.get_size_in_points())
+ verts, codes = text2path.get_text_path(prop, s, ismath=ismath)
+ path = Path(verts, codes)
+ if self.flipy():
+ width, height = self.get_canvas_width_height()
+ transform = (Affine2D()
+ .scale(fontsize / text2path.FONT_SCALE)
+ .rotate_deg(angle)
+ .translate(x, height - y))
+ else:
+ transform = (Affine2D()
+ .scale(fontsize / text2path.FONT_SCALE)
+ .rotate_deg(angle)
+ .translate(x, y))
+ color = gc.get_rgb()
+ gc.set_linewidth(0.0)
+ self.draw_path(gc, path, transform, rgbFace=color)
+
+ def get_text_width_height_descent(self, s, prop, ismath):
+ """
+ Get the width, height, and descent (offset from the bottom to the baseline), in
+ display coords, of the string *s* with `.FontProperties` *prop*.
+
+ Whitespace at the start and the end of *s* is included in the reported width.
+ """
+ fontsize = prop.get_size_in_points()
+
+ if ismath == 'TeX':
+ # todo: handle properties
+ return self.get_texmanager().get_text_width_height_descent(
+ s, fontsize, renderer=self)
+
+ dpi = self.points_to_pixels(72)
+ if ismath:
+ dims = self._text2path.mathtext_parser.parse(s, dpi, prop)
+ return dims[0:3] # return width, height, descent
+
+ flags = self._text2path._get_hinting_flag()
+ font = self._text2path._get_font(prop)
+ font.set_size(fontsize, dpi)
+ # the width and height of unrotated string
+ font.set_text(s, 0.0, flags=flags)
+ w, h = font.get_width_height()
+ d = font.get_descent()
+ w /= 64.0 # convert from subpixels
+ h /= 64.0
+ d /= 64.0
+ return w, h, d
+
+ def flipy(self):
+ """
+ Return whether y values increase from top to bottom.
+
+ Note that this only affects drawing of texts.
+ """
+ return True
+
+ def get_canvas_width_height(self):
+ """Return the canvas width and height in display coords."""
+ return 1, 1
+
+ def get_texmanager(self):
+ """Return the `.TexManager` instance."""
+ if self._texmanager is None:
+ self._texmanager = TexManager()
+ return self._texmanager
+
+ def new_gc(self):
+ """Return an instance of a `.GraphicsContextBase`."""
+ return GraphicsContextBase()
+
+ def points_to_pixels(self, points):
+ """
+ Convert points to display units.
+
+ You need to override this function (unless your backend
+ doesn't have a dpi, e.g., postscript or svg). Some imaging
+ systems assume some value for pixels per inch::
+
+ points to pixels = points * pixels_per_inch/72 * dpi/72
+
+ Parameters
+ ----------
+ points : float or array-like
+
+ Returns
+ -------
+ Points converted to pixels
+ """
+ return points
+
+ def start_rasterizing(self):
+ """
+ Switch to the raster renderer.
+
+ Used by `.MixedModeRenderer`.
+ """
+
+ def stop_rasterizing(self):
+ """
+ Switch back to the vector renderer and draw the contents of the raster
+ renderer as an image on the vector renderer.
+
+ Used by `.MixedModeRenderer`.
+ """
+
+ def start_filter(self):
+ """
+ Switch to a temporary renderer for image filtering effects.
+
+ Currently only supported by the agg renderer.
+ """
+
+ def stop_filter(self, filter_func):
+ """
+ Switch back to the original renderer. The contents of the temporary
+ renderer is processed with the *filter_func* and is drawn on the
+ original renderer as an image.
+
+ Currently only supported by the agg renderer.
+ """
+
+ def _draw_disabled(self):
+ """
+ Context manager to temporary disable drawing.
+
+ This is used for getting the drawn size of Artists. This lets us
+ run the draw process to update any Python state but does not pay the
+ cost of the draw_XYZ calls on the canvas.
+ """
+ no_ops = {
+ meth_name: lambda *args, **kwargs: None
+ for meth_name in dir(RendererBase)
+ if (meth_name.startswith("draw_")
+ or meth_name in ["open_group", "close_group"])
+ }
+
+ return _setattr_cm(self, **no_ops)
+
+
+class GraphicsContextBase:
+ """An abstract base class that provides color, line styles, etc."""
+
+ def __init__(self):
+ self._alpha = 1.0
+ self._forced_alpha = False # if True, _alpha overrides A from RGBA
+ self._antialiased = 1 # use 0, 1 not True, False for extension code
+ self._capstyle = CapStyle('butt')
+ self._cliprect = None
+ self._clippath = None
+ self._dashes = 0, None
+ self._joinstyle = JoinStyle('round')
+ self._linestyle = 'solid'
+ self._linewidth = 1
+ self._rgb = (0.0, 0.0, 0.0, 1.0)
+ self._hatch = None
+ self._hatch_color = colors.to_rgba(rcParams['hatch.color'])
+ self._hatch_linewidth = rcParams['hatch.linewidth']
+ self._url = None
+ self._gid = None
+ self._snap = None
+ self._sketch = None
+
+ def copy_properties(self, gc):
+ """Copy properties from *gc* to self."""
+ self._alpha = gc._alpha
+ self._forced_alpha = gc._forced_alpha
+ self._antialiased = gc._antialiased
+ self._capstyle = gc._capstyle
+ self._cliprect = gc._cliprect
+ self._clippath = gc._clippath
+ self._dashes = gc._dashes
+ self._joinstyle = gc._joinstyle
+ self._linestyle = gc._linestyle
+ self._linewidth = gc._linewidth
+ self._rgb = gc._rgb
+ self._hatch = gc._hatch
+ self._hatch_color = gc._hatch_color
+ self._hatch_linewidth = gc._hatch_linewidth
+ self._url = gc._url
+ self._gid = gc._gid
+ self._snap = gc._snap
+ self._sketch = gc._sketch
+
+ def restore(self):
+ """
+ Restore the graphics context from the stack - needed only
+ for backends that save graphics contexts on a stack.
+ """
+
+ def get_alpha(self):
+ """
+ Return the alpha value used for blending - not supported on all
+ backends.
+ """
+ return self._alpha
+
+ def get_antialiased(self):
+ """Return whether the object should try to do antialiased rendering."""
+ return self._antialiased
+
+ def get_capstyle(self):
+ """Return the `.CapStyle`."""
+ return self._capstyle.name
+
+ def get_clip_rectangle(self):
+ """
+ Return the clip rectangle as a `~matplotlib.transforms.Bbox` instance.
+ """
+ return self._cliprect
+
+ def get_clip_path(self):
+ """
+ Return the clip path in the form (path, transform), where path
+ is a `~.path.Path` instance, and transform is
+ an affine transform to apply to the path before clipping.
+ """
+ if self._clippath is not None:
+ tpath, tr = self._clippath.get_transformed_path_and_affine()
+ if np.all(np.isfinite(tpath.vertices)):
+ return tpath, tr
+ else:
+ _log.warning("Ill-defined clip_path detected. Returning None.")
+ return None, None
+ return None, None
+
+ def get_dashes(self):
+ """
+ Return the dash style as an (offset, dash-list) pair.
+
+ See `.set_dashes` for details.
+
+ Default value is (None, None).
+ """
+ return self._dashes
+
+ def get_forced_alpha(self):
+ """
+ Return whether the value given by get_alpha() should be used to
+ override any other alpha-channel values.
+ """
+ return self._forced_alpha
+
+ def get_joinstyle(self):
+ """Return the `.JoinStyle`."""
+ return self._joinstyle.name
+
+ def get_linewidth(self):
+ """Return the line width in points."""
+ return self._linewidth
+
+ def get_rgb(self):
+ """Return a tuple of three or four floats from 0-1."""
+ return self._rgb
+
+ def get_url(self):
+ """Return a url if one is set, None otherwise."""
+ return self._url
+
+ def get_gid(self):
+ """Return the object identifier if one is set, None otherwise."""
+ return self._gid
+
+ def get_snap(self):
+ """
+ Return the snap setting, which can be:
+
+ * True: snap vertices to the nearest pixel center
+ * False: leave vertices as-is
+ * None: (auto) If the path contains only rectilinear line segments,
+ round to the nearest pixel center
+ """
+ return self._snap
+
+ def set_alpha(self, alpha):
+ """
+ Set the alpha value used for blending - not supported on all backends.
+
+ If ``alpha=None`` (the default), the alpha components of the
+ foreground and fill colors will be used to set their respective
+ transparencies (where applicable); otherwise, ``alpha`` will override
+ them.
+ """
+ if alpha is not None:
+ self._alpha = alpha
+ self._forced_alpha = True
+ else:
+ self._alpha = 1.0
+ self._forced_alpha = False
+ self.set_foreground(self._rgb, isRGBA=True)
+
+ def set_antialiased(self, b):
+ """Set whether object should be drawn with antialiased rendering."""
+ # Use ints to make life easier on extension code trying to read the gc.
+ self._antialiased = int(bool(b))
+
+ @_docstring.interpd
+ def set_capstyle(self, cs):
+ """
+ Set how to draw endpoints of lines.
+
+ Parameters
+ ----------
+ cs : `.CapStyle` or %(CapStyle)s
+ """
+ self._capstyle = CapStyle(cs)
+
+ def set_clip_rectangle(self, rectangle):
+ """Set the clip rectangle to a `.Bbox` or None."""
+ self._cliprect = rectangle
+
+ def set_clip_path(self, path):
+ """Set the clip path to a `.TransformedPath` or None."""
+ _api.check_isinstance((transforms.TransformedPath, None), path=path)
+ self._clippath = path
+
+ def set_dashes(self, dash_offset, dash_list):
+ """
+ Set the dash style for the gc.
+
+ Parameters
+ ----------
+ dash_offset : float
+ Distance, in points, into the dash pattern at which to
+ start the pattern. It is usually set to 0.
+ dash_list : array-like or None
+ The on-off sequence as points. None specifies a solid line. All
+ values must otherwise be non-negative (:math:`\\ge 0`).
+
+ Notes
+ -----
+ See p. 666 of the PostScript
+ `Language Reference
+ `_
+ for more info.
+ """
+ if dash_list is not None:
+ dl = np.asarray(dash_list)
+ if np.any(dl < 0.0):
+ raise ValueError(
+ "All values in the dash list must be non-negative")
+ if dl.size and not np.any(dl > 0.0):
+ raise ValueError(
+ 'At least one value in the dash list must be positive')
+ self._dashes = dash_offset, dash_list
+
+ def set_foreground(self, fg, isRGBA=False):
+ """
+ Set the foreground color.
+
+ Parameters
+ ----------
+ fg : :mpltype:`color`
+ isRGBA : bool
+ If *fg* is known to be an ``(r, g, b, a)`` tuple, *isRGBA* can be
+ set to True to improve performance.
+ """
+ if self._forced_alpha and isRGBA:
+ self._rgb = fg[:3] + (self._alpha,)
+ elif self._forced_alpha:
+ self._rgb = colors.to_rgba(fg, self._alpha)
+ elif isRGBA:
+ self._rgb = fg
+ else:
+ self._rgb = colors.to_rgba(fg)
+
+ @_docstring.interpd
+ def set_joinstyle(self, js):
+ """
+ Set how to draw connections between line segments.
+
+ Parameters
+ ----------
+ js : `.JoinStyle` or %(JoinStyle)s
+ """
+ self._joinstyle = JoinStyle(js)
+
+ def set_linewidth(self, w):
+ """Set the linewidth in points."""
+ self._linewidth = float(w)
+
+ def set_url(self, url):
+ """Set the url for links in compatible backends."""
+ self._url = url
+
+ def set_gid(self, id):
+ """Set the id."""
+ self._gid = id
+
+ def set_snap(self, snap):
+ """
+ Set the snap setting which may be:
+
+ * True: snap vertices to the nearest pixel center
+ * False: leave vertices as-is
+ * None: (auto) If the path contains only rectilinear line segments,
+ round to the nearest pixel center
+ """
+ self._snap = snap
+
+ def set_hatch(self, hatch):
+ """Set the hatch style (for fills)."""
+ self._hatch = hatch
+
+ def get_hatch(self):
+ """Get the current hatch style."""
+ return self._hatch
+
+ def get_hatch_path(self, density=6.0):
+ """Return a `.Path` for the current hatch."""
+ hatch = self.get_hatch()
+ if hatch is None:
+ return None
+ return Path.hatch(hatch, density)
+
+ def get_hatch_color(self):
+ """Get the hatch color."""
+ return self._hatch_color
+
+ def set_hatch_color(self, hatch_color):
+ """Set the hatch color."""
+ self._hatch_color = hatch_color
+
+ def get_hatch_linewidth(self):
+ """Get the hatch linewidth."""
+ return self._hatch_linewidth
+
+ def set_hatch_linewidth(self, hatch_linewidth):
+ """Set the hatch linewidth."""
+ self._hatch_linewidth = hatch_linewidth
+
+ 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.
+
+ May return `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, default: 128
+ The length of the wiggle along the line, in pixels.
+ randomness : float, default: 16
+ The scale factor by which the length is shrunken or expanded.
+ """
+ self._sketch = (
+ None if scale is None
+ else (scale, length or 128., randomness or 16.))
+
+
+class TimerBase:
+ """
+ A base class for providing timer events, useful for things animations.
+ Backends need to implement a few specific methods in order to use their
+ own timing mechanisms so that the timer events are integrated into their
+ event loops.
+
+ Subclasses must override the following methods:
+
+ - ``_timer_start``: Backend-specific code for starting the timer.
+ - ``_timer_stop``: Backend-specific code for stopping the timer.
+
+ Subclasses may additionally override the following methods:
+
+ - ``_timer_set_single_shot``: Code for setting the timer to single shot
+ operating mode, if supported by the timer object. If not, the `Timer`
+ class itself will store the flag and the ``_on_timer`` method should be
+ overridden to support such behavior.
+
+ - ``_timer_set_interval``: Code for setting the interval on the timer, if
+ there is a method for doing so on the timer object.
+
+ - ``_on_timer``: The internal function that any timer object should call,
+ which will handle the task of running all callbacks that have been set.
+ """
+
+ def __init__(self, interval=None, callbacks=None):
+ """
+ Parameters
+ ----------
+ interval : int, default: 1000ms
+ The time between timer events in milliseconds. Will be stored as
+ ``timer.interval``.
+ callbacks : list[tuple[callable, tuple, dict]]
+ List of (func, args, kwargs) tuples that will be called upon timer
+ events. This list is accessible as ``timer.callbacks`` and can be
+ manipulated directly, or the functions `~.TimerBase.add_callback`
+ and `~.TimerBase.remove_callback` can be used.
+ """
+ self.callbacks = [] if callbacks is None else callbacks.copy()
+ # Set .interval and not ._interval to go through the property setter.
+ self.interval = 1000 if interval is None else interval
+ self.single_shot = False
+
+ def __del__(self):
+ """Need to stop timer and possibly disconnect timer."""
+ self._timer_stop()
+
+ @_api.delete_parameter("3.9", "interval", alternative="timer.interval")
+ def start(self, interval=None):
+ """
+ Start the timer object.
+
+ Parameters
+ ----------
+ interval : int, optional
+ Timer interval in milliseconds; overrides a previously set interval
+ if provided.
+ """
+ if interval is not None:
+ self.interval = interval
+ self._timer_start()
+
+ def stop(self):
+ """Stop the timer."""
+ self._timer_stop()
+
+ def _timer_start(self):
+ pass
+
+ def _timer_stop(self):
+ pass
+
+ @property
+ def interval(self):
+ """The time between timer events, in milliseconds."""
+ return self._interval
+
+ @interval.setter
+ def interval(self, interval):
+ # Force to int since none of the backends actually support fractional
+ # milliseconds, and some error or give warnings.
+ # Some backends also fail when interval == 0, so ensure >= 1 msec
+ interval = max(int(interval), 1)
+ self._interval = interval
+ self._timer_set_interval()
+
+ @property
+ def single_shot(self):
+ """Whether this timer should stop after a single run."""
+ return self._single
+
+ @single_shot.setter
+ def single_shot(self, ss):
+ self._single = ss
+ self._timer_set_single_shot()
+
+ def add_callback(self, func, *args, **kwargs):
+ """
+ Register *func* to be called by timer when the event fires. Any
+ additional arguments provided will be passed to *func*.
+
+ This function returns *func*, which makes it possible to use it as a
+ decorator.
+ """
+ self.callbacks.append((func, args, kwargs))
+ return func
+
+ def remove_callback(self, func, *args, **kwargs):
+ """
+ Remove *func* from list of callbacks.
+
+ *args* and *kwargs* are optional and used to distinguish between copies
+ of the same function registered to be called with different arguments.
+ This behavior is deprecated. In the future, ``*args, **kwargs`` won't
+ be considered anymore; to keep a specific callback removable by itself,
+ pass it to `add_callback` as a `functools.partial` object.
+ """
+ if args or kwargs:
+ _api.warn_deprecated(
+ "3.1", message="In a future version, Timer.remove_callback "
+ "will not take *args, **kwargs anymore, but remove all "
+ "callbacks where the callable matches; to keep a specific "
+ "callback removable by itself, pass it to add_callback as a "
+ "functools.partial object.")
+ self.callbacks.remove((func, args, kwargs))
+ else:
+ funcs = [c[0] for c in self.callbacks]
+ if func in funcs:
+ self.callbacks.pop(funcs.index(func))
+
+ def _timer_set_interval(self):
+ """Used to set interval on underlying timer object."""
+
+ def _timer_set_single_shot(self):
+ """Used to set single shot on underlying timer object."""
+
+ def _on_timer(self):
+ """
+ Runs all function that have been registered as callbacks. Functions
+ can return False (or 0) if they should not be called any more. If there
+ are no callbacks, the timer is automatically stopped.
+ """
+ for func, args, kwargs in self.callbacks:
+ ret = func(*args, **kwargs)
+ # docstring above explains why we use `if ret == 0` here,
+ # instead of `if not ret`.
+ # This will also catch `ret == False` as `False == 0`
+ # but does not annoy the linters
+ # https://docs.python.org/3/library/stdtypes.html#boolean-values
+ if ret == 0:
+ self.callbacks.remove((func, args, kwargs))
+
+ if len(self.callbacks) == 0:
+ self.stop()
+
+
+class Event:
+ """
+ A Matplotlib event.
+
+ The following attributes are defined and shown with their default values.
+ Subclasses may define additional attributes.
+
+ Attributes
+ ----------
+ name : str
+ The event name.
+ canvas : `FigureCanvasBase`
+ The backend-specific canvas instance generating the event.
+ guiEvent
+ The GUI event that triggered the Matplotlib event.
+ """
+
+ def __init__(self, name, canvas, guiEvent=None):
+ self.name = name
+ self.canvas = canvas
+ self.guiEvent = guiEvent
+
+ def _process(self):
+ """Process this event on ``self.canvas``, then unset ``guiEvent``."""
+ self.canvas.callbacks.process(self.name, self)
+ self.guiEvent = None
+
+
+class DrawEvent(Event):
+ """
+ An event triggered by a draw operation on the canvas.
+
+ In most backends, callbacks subscribed to this event will be fired after
+ the rendering is complete but before the screen is updated. Any extra
+ artists drawn to the canvas's renderer will be reflected without an
+ explicit call to ``blit``.
+
+ .. warning::
+
+ Calling ``canvas.draw`` and ``canvas.blit`` in these callbacks may
+ not be safe with all backends and may cause infinite recursion.
+
+ A DrawEvent has a number of special attributes in addition to those defined
+ by the parent `Event` class.
+
+ Attributes
+ ----------
+ renderer : `RendererBase`
+ The renderer for the draw event.
+ """
+ def __init__(self, name, canvas, renderer):
+ super().__init__(name, canvas)
+ self.renderer = renderer
+
+
+class ResizeEvent(Event):
+ """
+ An event triggered by a canvas resize.
+
+ A ResizeEvent has a number of special attributes in addition to those
+ defined by the parent `Event` class.
+
+ Attributes
+ ----------
+ width : int
+ Width of the canvas in pixels.
+ height : int
+ Height of the canvas in pixels.
+ """
+
+ def __init__(self, name, canvas):
+ super().__init__(name, canvas)
+ self.width, self.height = canvas.get_width_height()
+
+
+class CloseEvent(Event):
+ """An event triggered by a figure being closed."""
+
+
+class LocationEvent(Event):
+ """
+ An event that has a screen location.
+
+ A LocationEvent has a number of special attributes in addition to those
+ defined by the parent `Event` class.
+
+ Attributes
+ ----------
+ x, y : int or None
+ Event location in pixels from bottom left of canvas.
+ inaxes : `~matplotlib.axes.Axes` or None
+ The `~.axes.Axes` instance over which the mouse is, if any.
+ xdata, ydata : float or None
+ Data coordinates of the mouse within *inaxes*, or *None* if the mouse
+ is not over an Axes.
+ modifiers : frozenset
+ The keyboard modifiers currently being pressed (except for KeyEvent).
+ """
+
+ _last_axes_ref = None
+
+ def __init__(self, name, canvas, x, y, guiEvent=None, *, modifiers=None):
+ super().__init__(name, canvas, guiEvent=guiEvent)
+ # x position - pixels from left of canvas
+ self.x = int(x) if x is not None else x
+ # y position - pixels from right of canvas
+ self.y = int(y) if y is not None else y
+ self.inaxes = None # the Axes instance the mouse is over
+ self.xdata = None # x coord of mouse in data coords
+ self.ydata = None # y coord of mouse in data coords
+ self.modifiers = frozenset(modifiers if modifiers is not None else [])
+
+ if x is None or y is None:
+ # cannot check if event was in Axes if no (x, y) info
+ return
+
+ self._set_inaxes(self.canvas.inaxes((x, y))
+ if self.canvas.mouse_grabber is None else
+ self.canvas.mouse_grabber,
+ (x, y))
+
+ # Splitting _set_inaxes out is useful for the axes_leave_event handler: it
+ # needs to generate synthetic LocationEvents with manually-set inaxes. In
+ # that latter case, xy has already been cast to int so it can directly be
+ # read from self.x, self.y; in the normal case, however, it is more
+ # accurate to pass the untruncated float x, y values passed to the ctor.
+
+ def _set_inaxes(self, inaxes, xy=None):
+ self.inaxes = inaxes
+ if inaxes is not None:
+ try:
+ self.xdata, self.ydata = inaxes.transData.inverted().transform(
+ xy if xy is not None else (self.x, self.y))
+ except ValueError:
+ pass
+
+
+class MouseButton(IntEnum):
+ LEFT = 1
+ MIDDLE = 2
+ RIGHT = 3
+ BACK = 8
+ FORWARD = 9
+
+
+class MouseEvent(LocationEvent):
+ """
+ A mouse event ('button_press_event', 'button_release_event', \
+'scroll_event', 'motion_notify_event').
+
+ A MouseEvent has a number of special attributes in addition to those
+ defined by the parent `Event` and `LocationEvent` classes.
+
+ Attributes
+ ----------
+ button : None or `MouseButton` or {'up', 'down'}
+ The button pressed. 'up' and 'down' are used for scroll events.
+
+ Note that LEFT and RIGHT actually refer to the "primary" and
+ "secondary" buttons, i.e. if the user inverts their left and right
+ buttons ("left-handed setting") then the LEFT button will be the one
+ physically on the right.
+
+ If this is unset, *name* is "scroll_event", and *step* is nonzero, then
+ this will be set to "up" or "down" depending on the sign of *step*.
+
+ buttons : None or frozenset
+ For 'motion_notify_event', the mouse buttons currently being pressed
+ (a set of zero or more MouseButtons);
+ for other events, None.
+
+ .. note::
+ For 'motion_notify_event', this attribute is more accurate than
+ the ``button`` (singular) attribute, which is obtained from the last
+ 'button_press_event' or 'button_release_event' that occurred within
+ the canvas (and thus 1. be wrong if the last change in mouse state
+ occurred when the canvas did not have focus, and 2. cannot report
+ when multiple buttons are pressed).
+
+ This attribute is not set for 'button_press_event' and
+ 'button_release_event' because GUI toolkits are inconsistent as to
+ whether they report the button state *before* or *after* the
+ press/release occurred.
+
+ .. warning::
+ On macOS, the Tk backends only report a single button even if
+ multiple buttons are pressed.
+
+ key : None or str
+ The key pressed when the mouse event triggered, e.g. 'shift'.
+ See `KeyEvent`.
+
+ .. warning::
+ This key is currently obtained from the last 'key_press_event' or
+ 'key_release_event' that occurred within the canvas. Thus, if the
+ last change of keyboard state occurred while the canvas did not have
+ focus, this attribute will be wrong. On the other hand, the
+ ``modifiers`` attribute should always be correct, but it can only
+ report on modifier keys.
+
+ step : float
+ The number of scroll steps (positive for 'up', negative for 'down').
+ This applies only to 'scroll_event' and defaults to 0 otherwise.
+
+ dblclick : bool
+ Whether the event is a double-click. This applies only to
+ 'button_press_event' and is False otherwise. In particular, it's
+ not used in 'button_release_event'.
+
+ Examples
+ --------
+ ::
+
+ def on_press(event):
+ print('you pressed', event.button, event.xdata, event.ydata)
+
+ cid = fig.canvas.mpl_connect('button_press_event', on_press)
+ """
+
+ def __init__(self, name, canvas, x, y, button=None, key=None,
+ step=0, dblclick=False, guiEvent=None, *,
+ buttons=None, modifiers=None):
+ super().__init__(
+ name, canvas, x, y, guiEvent=guiEvent, modifiers=modifiers)
+ if button in MouseButton.__members__.values():
+ button = MouseButton(button)
+ if name == "scroll_event" and button is None:
+ if step > 0:
+ button = "up"
+ elif step < 0:
+ button = "down"
+ self.button = button
+ if name == "motion_notify_event":
+ self.buttons = frozenset(buttons if buttons is not None else [])
+ else:
+ # We don't support 'buttons' for button_press/release_event because
+ # toolkits are inconsistent as to whether they report the state
+ # before or after the event.
+ if buttons:
+ raise ValueError(
+ "'buttons' is only supported for 'motion_notify_event'")
+ self.buttons = None
+ self.key = key
+ self.step = step
+ self.dblclick = dblclick
+
+ def __str__(self):
+ return (f"{self.name}: "
+ f"xy=({self.x}, {self.y}) xydata=({self.xdata}, {self.ydata}) "
+ f"button={self.button} dblclick={self.dblclick} "
+ f"inaxes={self.inaxes}")
+
+
+class PickEvent(Event):
+ """
+ A pick event.
+
+ This event is fired when the user picks a location on the canvas
+ sufficiently close to an artist that has been made pickable with
+ `.Artist.set_picker`.
+
+ A PickEvent has a number of special attributes in addition to those defined
+ by the parent `Event` class.
+
+ Attributes
+ ----------
+ mouseevent : `MouseEvent`
+ The mouse event that generated the pick.
+ artist : `~matplotlib.artist.Artist`
+ The picked artist. Note that artists are not pickable by default
+ (see `.Artist.set_picker`).
+ other
+ Additional attributes may be present depending on the type of the
+ picked object; e.g., a `.Line2D` pick may define different extra
+ attributes than a `.PatchCollection` pick.
+
+ Examples
+ --------
+ Bind a function ``on_pick()`` to pick events, that prints the coordinates
+ of the picked data point::
+
+ ax.plot(np.rand(100), 'o', picker=5) # 5 points tolerance
+
+ def on_pick(event):
+ line = event.artist
+ xdata, ydata = line.get_data()
+ ind = event.ind
+ print(f'on pick line: {xdata[ind]:.3f}, {ydata[ind]:.3f}')
+
+ cid = fig.canvas.mpl_connect('pick_event', on_pick)
+ """
+
+ def __init__(self, name, canvas, mouseevent, artist,
+ guiEvent=None, **kwargs):
+ if guiEvent is None:
+ guiEvent = mouseevent.guiEvent
+ super().__init__(name, canvas, guiEvent)
+ self.mouseevent = mouseevent
+ self.artist = artist
+ self.__dict__.update(kwargs)
+
+
+class KeyEvent(LocationEvent):
+ """
+ A key event (key press, key release).
+
+ A KeyEvent has a number of special attributes in addition to those defined
+ by the parent `Event` and `LocationEvent` classes.
+
+ Attributes
+ ----------
+ key : None or str
+ The key(s) pressed. Could be *None*, a single case sensitive Unicode
+ character ("g", "G", "#", etc.), a special key ("control", "shift",
+ "f1", "up", etc.) or a combination of the above (e.g., "ctrl+alt+g",
+ "ctrl+alt+G").
+
+ Notes
+ -----
+ Modifier keys will be prefixed to the pressed key and will be in the order
+ "ctrl", "alt", "super". The exception to this rule is when the pressed key
+ is itself a modifier key, therefore "ctrl+alt" and "alt+control" can both
+ be valid key values.
+
+ Examples
+ --------
+ ::
+
+ def on_key(event):
+ print('you pressed', event.key, event.xdata, event.ydata)
+
+ cid = fig.canvas.mpl_connect('key_press_event', on_key)
+ """
+
+ def __init__(self, name, canvas, key, x=0, y=0, guiEvent=None):
+ super().__init__(name, canvas, x, y, guiEvent=guiEvent)
+ self.key = key
+
+
+# Default callback for key events.
+def _key_handler(event):
+ # Dead reckoning of key.
+ if event.name == "key_press_event":
+ event.canvas._key = event.key
+ elif event.name == "key_release_event":
+ event.canvas._key = None
+
+
+# Default callback for mouse events.
+def _mouse_handler(event):
+ # Dead-reckoning of button and key.
+ if event.name == "button_press_event":
+ event.canvas._button = event.button
+ elif event.name == "button_release_event":
+ event.canvas._button = None
+ elif event.name == "motion_notify_event" and event.button is None:
+ event.button = event.canvas._button
+ if event.key is None:
+ event.key = event.canvas._key
+ # Emit axes_enter/axes_leave.
+ if event.name == "motion_notify_event":
+ last_ref = LocationEvent._last_axes_ref
+ last_axes = last_ref() if last_ref else None
+ if last_axes != event.inaxes:
+ if last_axes is not None:
+ # Create a synthetic LocationEvent for the axes_leave_event.
+ # Its inaxes attribute needs to be manually set (because the
+ # cursor is actually *out* of that Axes at that point); this is
+ # done with the internal _set_inaxes method which ensures that
+ # the xdata and ydata attributes are also correct.
+ try:
+ canvas = last_axes.get_figure(root=True).canvas
+ leave_event = LocationEvent(
+ "axes_leave_event", canvas,
+ event.x, event.y, event.guiEvent,
+ modifiers=event.modifiers)
+ leave_event._set_inaxes(last_axes)
+ canvas.callbacks.process("axes_leave_event", leave_event)
+ except Exception:
+ pass # The last canvas may already have been torn down.
+ if event.inaxes is not None:
+ event.canvas.callbacks.process("axes_enter_event", event)
+ LocationEvent._last_axes_ref = (
+ weakref.ref(event.inaxes) if event.inaxes else None)
+
+
+def _get_renderer(figure, print_method=None):
+ """
+ Get the renderer that would be used to save a `.Figure`.
+
+ If you need a renderer without any active draw methods use
+ renderer._draw_disabled to temporary patch them out at your call site.
+ """
+ # This is implemented by triggering a draw, then immediately jumping out of
+ # Figure.draw() by raising an exception.
+
+ class Done(Exception):
+ pass
+
+ def _draw(renderer): raise Done(renderer)
+
+ with cbook._setattr_cm(figure, draw=_draw), ExitStack() as stack:
+ if print_method is None:
+ fmt = figure.canvas.get_default_filetype()
+ # Even for a canvas' default output type, a canvas switch may be
+ # needed, e.g. for FigureCanvasBase.
+ print_method = stack.enter_context(
+ figure.canvas._switch_canvas_and_return_print_method(fmt))
+ try:
+ print_method(io.BytesIO())
+ except Done as exc:
+ renderer, = exc.args
+ return renderer
+ else:
+ raise RuntimeError(f"{print_method} did not call Figure.draw, so "
+ f"no renderer is available")
+
+
+def _no_output_draw(figure):
+ # _no_output_draw was promoted to the figure level, but
+ # keep this here in case someone was calling it...
+ figure.draw_without_rendering()
+
+
+def _is_non_interactive_terminal_ipython(ip):
+ """
+ Return whether we are in a terminal IPython, but non interactive.
+
+ When in _terminal_ IPython, ip.parent will have and `interact` attribute,
+ if this attribute is False we do not setup eventloop integration as the
+ user will _not_ interact with IPython. In all other case (ZMQKernel, or is
+ interactive), we do.
+ """
+ return (hasattr(ip, 'parent')
+ and (ip.parent is not None)
+ and getattr(ip.parent, 'interact', None) is False)
+
+
+@contextmanager
+def _allow_interrupt(prepare_notifier, handle_sigint):
+ """
+ A context manager that allows terminating a plot by sending a SIGINT. It
+ is necessary because the running backend prevents the Python interpreter
+ from running and processing signals (i.e., to raise a KeyboardInterrupt).
+ To solve this, one needs to somehow wake up the interpreter and make it
+ close the plot window. We do this by using the signal.set_wakeup_fd()
+ function which organizes a write of the signal number into a socketpair.
+ A backend-specific function, *prepare_notifier*, arranges to listen to
+ the pair's read socket while the event loop is running. (If it returns a
+ notifier object, that object is kept alive while the context manager runs.)
+
+ If SIGINT was indeed caught, after exiting the on_signal() function the
+ interpreter reacts to the signal according to the handler function which
+ had been set up by a signal.signal() call; here, we arrange to call the
+ backend-specific *handle_sigint* function, passing the notifier object
+ as returned by prepare_notifier(). Finally, we call the old SIGINT
+ handler with the same arguments that were given to our custom handler.
+
+ We do this only if the old handler for SIGINT was not None, which means
+ that a non-python handler was installed, i.e. in Julia, and not SIG_IGN
+ which means we should ignore the interrupts.
+
+ Parameters
+ ----------
+ prepare_notifier : Callable[[socket.socket], object]
+ handle_sigint : Callable[[object], object]
+ """
+
+ old_sigint_handler = signal.getsignal(signal.SIGINT)
+ if old_sigint_handler in (None, signal.SIG_IGN, signal.SIG_DFL):
+ yield
+ return
+
+ handler_args = None
+ wsock, rsock = socket.socketpair()
+ wsock.setblocking(False)
+ rsock.setblocking(False)
+ old_wakeup_fd = signal.set_wakeup_fd(wsock.fileno())
+ notifier = prepare_notifier(rsock)
+
+ def save_args_and_handle_sigint(*args):
+ nonlocal handler_args, notifier
+ handler_args = args
+ handle_sigint(notifier)
+ notifier = None
+
+ signal.signal(signal.SIGINT, save_args_and_handle_sigint)
+ try:
+ yield
+ finally:
+ wsock.close()
+ rsock.close()
+ signal.set_wakeup_fd(old_wakeup_fd)
+ signal.signal(signal.SIGINT, old_sigint_handler)
+ if handler_args is not None:
+ old_sigint_handler(*handler_args)
+
+
+class FigureCanvasBase:
+ """
+ The canvas the figure renders into.
+
+ Attributes
+ ----------
+ figure : `~matplotlib.figure.Figure`
+ A high-level figure instance.
+ """
+
+ # Set to one of {"qt", "gtk3", "gtk4", "wx", "tk", "macosx"} if an
+ # interactive framework is required, or None otherwise.
+ required_interactive_framework = None
+
+ # The manager class instantiated by new_manager.
+ # (This is defined as a classproperty because the manager class is
+ # currently defined *after* the canvas class, but one could also assign
+ # ``FigureCanvasBase.manager_class = FigureManagerBase``
+ # after defining both classes.)
+ manager_class = _api.classproperty(lambda cls: FigureManagerBase)
+
+ events = [
+ 'resize_event',
+ 'draw_event',
+ 'key_press_event',
+ 'key_release_event',
+ 'button_press_event',
+ 'button_release_event',
+ 'scroll_event',
+ 'motion_notify_event',
+ 'pick_event',
+ 'figure_enter_event',
+ 'figure_leave_event',
+ 'axes_enter_event',
+ 'axes_leave_event',
+ 'close_event'
+ ]
+
+ fixed_dpi = None
+
+ filetypes = _default_filetypes
+
+ @_api.classproperty
+ def supports_blit(cls):
+ """If this Canvas sub-class supports blitting."""
+ return (hasattr(cls, "copy_from_bbox")
+ and hasattr(cls, "restore_region"))
+
+ def __init__(self, figure=None):
+ from matplotlib.figure import Figure
+ self._fix_ipython_backend2gui()
+ self._is_idle_drawing = True
+ self._is_saving = False
+ if figure is None:
+ figure = Figure()
+ figure.set_canvas(self)
+ self.figure = figure
+ self.manager = None
+ self.widgetlock = widgets.LockDraw()
+ self._button = None # the button pressed
+ self._key = None # the key pressed
+ self.mouse_grabber = None # the Axes currently grabbing mouse
+ self.toolbar = None # NavigationToolbar2 will set me
+ self._is_idle_drawing = False
+ # We don't want to scale up the figure DPI more than once.
+ figure._original_dpi = figure.dpi
+ self._device_pixel_ratio = 1
+ super().__init__() # Typically the GUI widget init (if any).
+
+ callbacks = property(lambda self: self.figure._canvas_callbacks)
+ button_pick_id = property(lambda self: self.figure._button_pick_id)
+ scroll_pick_id = property(lambda self: self.figure._scroll_pick_id)
+
+ @classmethod
+ @functools.cache
+ def _fix_ipython_backend2gui(cls):
+ # Fix hard-coded module -> toolkit mapping in IPython (used for
+ # `ipython --auto`). This cannot be done at import time due to
+ # ordering issues, so we do it when creating a canvas, and should only
+ # be done once per class (hence the `cache`).
+
+ # This function will not be needed when Python 3.12, the latest version
+ # supported by IPython < 8.24, reaches end-of-life in late 2028.
+ # At that time this function can be made a no-op and deprecated.
+ mod_ipython = sys.modules.get("IPython")
+ if mod_ipython is None or mod_ipython.version_info[:2] >= (8, 24):
+ # Use of backend2gui is not needed for IPython >= 8.24 as the
+ # functionality has been moved to Matplotlib.
+ return
+
+ import IPython
+ ip = IPython.get_ipython()
+ if not ip:
+ return
+ from IPython.core import pylabtools as pt
+ if (not hasattr(pt, "backend2gui")
+ or not hasattr(ip, "enable_matplotlib")):
+ # In case we ever move the patch to IPython and remove these APIs,
+ # don't break on our side.
+ return
+ backend2gui_rif = {
+ "qt": "qt",
+ "gtk3": "gtk3",
+ "gtk4": "gtk4",
+ "wx": "wx",
+ "macosx": "osx",
+ }.get(cls.required_interactive_framework)
+ if backend2gui_rif:
+ if _is_non_interactive_terminal_ipython(ip):
+ ip.enable_gui(backend2gui_rif)
+
+ @classmethod
+ def new_manager(cls, figure, num):
+ """
+ Create a new figure manager for *figure*, using this canvas class.
+
+ Notes
+ -----
+ This method should not be reimplemented in subclasses. If
+ custom manager creation logic is needed, please reimplement
+ ``FigureManager.create_with_canvas``.
+ """
+ return cls.manager_class.create_with_canvas(cls, figure, num)
+
+ @contextmanager
+ def _idle_draw_cntx(self):
+ self._is_idle_drawing = True
+ try:
+ yield
+ finally:
+ self._is_idle_drawing = False
+
+ def is_saving(self):
+ """
+ Return whether the renderer is in the process of saving
+ to a file, rather than rendering for an on-screen buffer.
+ """
+ return self._is_saving
+
+ def blit(self, bbox=None):
+ """Blit the canvas in bbox (default entire canvas)."""
+
+ def inaxes(self, xy):
+ """
+ Return the topmost visible `~.axes.Axes` containing the point *xy*.
+
+ Parameters
+ ----------
+ xy : (float, float)
+ (x, y) pixel positions from left/bottom of the canvas.
+
+ Returns
+ -------
+ `~matplotlib.axes.Axes` or None
+ The topmost visible Axes containing the point, or None if there
+ is no Axes at the point.
+ """
+ axes_list = [a for a in self.figure.get_axes()
+ if a.patch.contains_point(xy) and a.get_visible()]
+ if axes_list:
+ axes = cbook._topmost_artist(axes_list)
+ else:
+ axes = None
+
+ return axes
+
+ def grab_mouse(self, ax):
+ """
+ Set the child `~.axes.Axes` which is grabbing the mouse events.
+
+ Usually called by the widgets themselves. It is an error to call this
+ if the mouse is already grabbed by another Axes.
+ """
+ if self.mouse_grabber not in (None, ax):
+ raise RuntimeError("Another Axes already grabs mouse input")
+ self.mouse_grabber = ax
+
+ def release_mouse(self, ax):
+ """
+ Release the mouse grab held by the `~.axes.Axes` *ax*.
+
+ Usually called by the widgets. It is ok to call this even if *ax*
+ doesn't have the mouse grab currently.
+ """
+ if self.mouse_grabber is ax:
+ self.mouse_grabber = None
+
+ def set_cursor(self, cursor):
+ """
+ Set the current cursor.
+
+ This may have no effect if the backend does not display anything.
+
+ If required by the backend, this method should trigger an update in
+ the backend event loop after the cursor is set, as this method may be
+ called e.g. before a long-running task during which the GUI is not
+ updated.
+
+ Parameters
+ ----------
+ cursor : `.Cursors`
+ The cursor to display over the canvas. Note: some backends may
+ change the cursor for the entire window.
+ """
+
+ def draw(self, *args, **kwargs):
+ """
+ Render the `.Figure`.
+
+ This method must walk the artist tree, even if no output is produced,
+ because it triggers deferred work that users may want to access
+ before saving output to disk. For example computing limits,
+ auto-limits, and tick values.
+ """
+
+ def draw_idle(self, *args, **kwargs):
+ """
+ Request a widget redraw once control returns to the GUI event loop.
+
+ Even if multiple calls to `draw_idle` occur before control returns
+ to the GUI event loop, the figure will only be rendered once.
+
+ Notes
+ -----
+ Backends may choose to override the method and implement their own
+ strategy to prevent multiple renderings.
+
+ """
+ if not self._is_idle_drawing:
+ with self._idle_draw_cntx():
+ self.draw(*args, **kwargs)
+
+ @property
+ def device_pixel_ratio(self):
+ """
+ The ratio of physical to logical pixels used for the canvas on screen.
+
+ By default, this is 1, meaning physical and logical pixels are the same
+ size. Subclasses that support High DPI screens may set this property to
+ indicate that said ratio is different. All Matplotlib interaction,
+ unless working directly with the canvas, remains in logical pixels.
+
+ """
+ return self._device_pixel_ratio
+
+ def _set_device_pixel_ratio(self, ratio):
+ """
+ Set the ratio of physical to logical pixels used for the canvas.
+
+ Subclasses that support High DPI screens can set this property to
+ indicate that said ratio is different. The canvas itself will be
+ created at the physical size, while the client side will use the
+ logical size. Thus the DPI of the Figure will change to be scaled by
+ this ratio. Implementations that support High DPI screens should use
+ physical pixels for events so that transforms back to Axes space are
+ correct.
+
+ By default, this is 1, meaning physical and logical pixels are the same
+ size.
+
+ Parameters
+ ----------
+ ratio : float
+ The ratio of logical to physical pixels used for the canvas.
+
+ Returns
+ -------
+ bool
+ Whether the ratio has changed. Backends may interpret this as a
+ signal to resize the window, repaint the canvas, or change any
+ other relevant properties.
+ """
+ if self._device_pixel_ratio == ratio:
+ return False
+ # In cases with mixed resolution displays, we need to be careful if the
+ # device pixel ratio changes - in this case we need to resize the
+ # canvas accordingly. Some backends provide events that indicate a
+ # change in DPI, but those that don't will update this before drawing.
+ dpi = ratio * self.figure._original_dpi
+ self.figure._set_dpi(dpi, forward=False)
+ self._device_pixel_ratio = ratio
+ return True
+
+ def get_width_height(self, *, physical=False):
+ """
+ Return the figure width and height in integral points or pixels.
+
+ When the figure is used on High DPI screens (and the backend supports
+ it), the truncation to integers occurs after scaling by the device
+ pixel ratio.
+
+ Parameters
+ ----------
+ physical : bool, default: False
+ Whether to return true physical pixels or logical pixels. Physical
+ pixels may be used by backends that support HiDPI, but still
+ configure the canvas using its actual size.
+
+ Returns
+ -------
+ width, height : int
+ The size of the figure, in points or pixels, depending on the
+ backend.
+ """
+ return tuple(int(size / (1 if physical else self.device_pixel_ratio))
+ for size in self.figure.bbox.max)
+
+ @classmethod
+ def get_supported_filetypes(cls):
+ """Return dict of savefig file formats supported by this backend."""
+ return cls.filetypes
+
+ @classmethod
+ def get_supported_filetypes_grouped(cls):
+ """
+ Return a dict of savefig file formats supported by this backend,
+ where the keys are a file type name, such as 'Joint Photographic
+ Experts Group', and the values are a list of filename extensions used
+ for that filetype, such as ['jpg', 'jpeg'].
+ """
+ groupings = {}
+ for ext, name in cls.filetypes.items():
+ groupings.setdefault(name, []).append(ext)
+ groupings[name].sort()
+ return groupings
+
+ @contextmanager
+ def _switch_canvas_and_return_print_method(self, fmt, backend=None):
+ """
+ Context manager temporarily setting the canvas for saving the figure::
+
+ with (canvas._switch_canvas_and_return_print_method(fmt, backend)
+ as print_method):
+ # ``print_method`` is a suitable ``print_{fmt}`` method, and
+ # the figure's canvas is temporarily switched to the method's
+ # canvas within the with... block. ``print_method`` is also
+ # wrapped to suppress extra kwargs passed by ``print_figure``.
+
+ Parameters
+ ----------
+ fmt : str
+ If *backend* is None, then determine a suitable canvas class for
+ saving to format *fmt* -- either the current canvas class, if it
+ supports *fmt*, or whatever `get_registered_canvas_class` returns;
+ switch the figure canvas to that canvas class.
+ backend : str or None, default: None
+ If not None, switch the figure canvas to the ``FigureCanvas`` class
+ of the given backend.
+ """
+ canvas = None
+ if backend is not None:
+ # Return a specific canvas class, if requested.
+ from .backends.registry import backend_registry
+ canvas_class = backend_registry.load_backend_module(backend).FigureCanvas
+ if not hasattr(canvas_class, f"print_{fmt}"):
+ raise ValueError(
+ f"The {backend!r} backend does not support {fmt} output")
+ canvas = canvas_class(self.figure)
+ elif hasattr(self, f"print_{fmt}"):
+ # Return the current canvas if it supports the requested format.
+ canvas = self
+ else:
+ # Return a default canvas for the requested format, if it exists.
+ canvas_class = get_registered_canvas_class(fmt)
+ if canvas_class is None:
+ raise ValueError(
+ "Format {!r} is not supported (supported formats: {})".format(
+ fmt, ", ".join(sorted(self.get_supported_filetypes()))))
+ canvas = canvas_class(self.figure)
+ canvas._is_saving = self._is_saving
+ meth = getattr(canvas, f"print_{fmt}")
+ mod = (meth.func.__module__
+ if hasattr(meth, "func") # partialmethod, e.g. backend_wx.
+ else meth.__module__)
+ if mod.startswith(("matplotlib.", "mpl_toolkits.")):
+ optional_kws = { # Passed by print_figure for other renderers.
+ "dpi", "facecolor", "edgecolor", "orientation",
+ "bbox_inches_restore"}
+ skip = optional_kws - {*inspect.signature(meth).parameters}
+ print_method = functools.wraps(meth)(lambda *args, **kwargs: meth(
+ *args, **{k: v for k, v in kwargs.items() if k not in skip}))
+ else: # Let third-parties do as they see fit.
+ print_method = meth
+ try:
+ yield print_method
+ finally:
+ self.figure.canvas = self
+
+ def print_figure(
+ self, filename, dpi=None, facecolor=None, edgecolor=None,
+ orientation='portrait', format=None, *,
+ bbox_inches=None, pad_inches=None, bbox_extra_artists=None,
+ backend=None, **kwargs):
+ """
+ Render the figure to hardcopy. Set the figure patch face and edge
+ colors. This is useful because some of the GUIs have a gray figure
+ face color background and you'll probably want to override this on
+ hardcopy.
+
+ Parameters
+ ----------
+ filename : str or path-like or file-like
+ The file where the figure is saved.
+
+ dpi : float, default: :rc:`savefig.dpi`
+ The dots per inch to save the figure in.
+
+ 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.
+
+ orientation : {'landscape', 'portrait'}, default: 'portrait'
+ Only currently applies to PostScript printing.
+
+ format : str, optional
+ Force a specific file format. If not given, the format is inferred
+ from the *filename* extension, and if that fails from
+ :rc:`savefig.format`.
+
+ bbox_inches : 'tight' 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.
+
+ bbox_extra_artists : list of `~matplotlib.artist.Artist`, optional
+ A list of extra artists that will be considered when the
+ tight bbox is calculated.
+
+ 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://...".
+ """
+ if format is None:
+ # get format from filename, or from backend's default filetype
+ if isinstance(filename, os.PathLike):
+ filename = os.fspath(filename)
+ if isinstance(filename, str):
+ format = os.path.splitext(filename)[1][1:]
+ if format is None or format == '':
+ format = self.get_default_filetype()
+ if isinstance(filename, str):
+ filename = filename.rstrip('.') + '.' + format
+ format = format.lower()
+
+ if dpi is None:
+ dpi = rcParams['savefig.dpi']
+ if dpi == 'figure':
+ dpi = getattr(self.figure, '_original_dpi', self.figure.dpi)
+
+ # Remove the figure manager, if any, to avoid resizing the GUI widget.
+ with (cbook._setattr_cm(self, manager=None),
+ self._switch_canvas_and_return_print_method(format, backend)
+ as print_method,
+ cbook._setattr_cm(self.figure, dpi=dpi),
+ cbook._setattr_cm(self.figure.canvas, _device_pixel_ratio=1),
+ cbook._setattr_cm(self.figure.canvas, _is_saving=True),
+ ExitStack() as stack):
+
+ for prop in ["facecolor", "edgecolor"]:
+ color = locals()[prop]
+ if color is None:
+ color = rcParams[f"savefig.{prop}"]
+ if not cbook._str_equal(color, "auto"):
+ stack.enter_context(self.figure._cm_set(**{prop: color}))
+
+ if bbox_inches is None:
+ bbox_inches = rcParams['savefig.bbox']
+
+ layout_engine = self.figure.get_layout_engine()
+ if layout_engine is not None or bbox_inches == "tight":
+ # we need to trigger a draw before printing to make sure
+ # CL works. "tight" also needs a draw to get the right
+ # locations:
+ renderer = _get_renderer(
+ self.figure,
+ functools.partial(
+ print_method, orientation=orientation)
+ )
+ # we do this instead of `self.figure.draw_without_rendering`
+ # so that we can inject the orientation
+ with getattr(renderer, "_draw_disabled", nullcontext)():
+ self.figure.draw(renderer)
+ if bbox_inches:
+ if bbox_inches == "tight":
+ bbox_inches = self.figure.get_tightbbox(
+ renderer, bbox_extra_artists=bbox_extra_artists)
+ if (isinstance(layout_engine, ConstrainedLayoutEngine) and
+ pad_inches == "layout"):
+ h_pad = layout_engine.get()["h_pad"]
+ w_pad = layout_engine.get()["w_pad"]
+ else:
+ if pad_inches in [None, "layout"]:
+ pad_inches = rcParams['savefig.pad_inches']
+ h_pad = w_pad = pad_inches
+ bbox_inches = bbox_inches.padded(w_pad, h_pad)
+
+ # call adjust_bbox to save only the given area
+ restore_bbox = _tight_bbox.adjust_bbox(
+ self.figure, bbox_inches, self.figure.canvas.fixed_dpi)
+
+ _bbox_inches_restore = (bbox_inches, restore_bbox)
+ else:
+ _bbox_inches_restore = None
+
+ # we have already done layout above, so turn it off:
+ stack.enter_context(self.figure._cm_set(layout_engine='none'))
+ try:
+ # _get_renderer may change the figure dpi (as vector formats
+ # force the figure dpi to 72), so we need to set it again here.
+ with cbook._setattr_cm(self.figure, dpi=dpi):
+ result = print_method(
+ filename,
+ facecolor=facecolor,
+ edgecolor=edgecolor,
+ orientation=orientation,
+ bbox_inches_restore=_bbox_inches_restore,
+ **kwargs)
+ finally:
+ if bbox_inches and restore_bbox:
+ restore_bbox()
+
+ return result
+
+ @classmethod
+ def get_default_filetype(cls):
+ """
+ Return the default savefig file format as specified in
+ :rc:`savefig.format`.
+
+ The returned string does not include a period. This method is
+ overridden in backends that only support a single file type.
+ """
+ return rcParams['savefig.format']
+
+ def get_default_filename(self):
+ """
+ Return a suitable default filename, including the extension.
+ """
+ default_basename = (
+ self.manager.get_window_title()
+ if self.manager is not None
+ else ''
+ )
+ default_basename = default_basename or 'image'
+ # Characters to be avoided in a NT path:
+ # https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#naming_conventions
+ # plus ' '
+ removed_chars = '<>:"/\\|?*\0 '
+ default_basename = default_basename.translate(
+ {ord(c): "_" for c in removed_chars})
+ default_filetype = self.get_default_filetype()
+ return f'{default_basename}.{default_filetype}'
+
+ def mpl_connect(self, s, func):
+ """
+ Bind function *func* to event *s*.
+
+ Parameters
+ ----------
+ s : str
+ One of the following events ids:
+
+ - 'button_press_event'
+ - 'button_release_event'
+ - 'draw_event'
+ - 'key_press_event'
+ - 'key_release_event'
+ - 'motion_notify_event'
+ - 'pick_event'
+ - 'resize_event'
+ - 'scroll_event'
+ - 'figure_enter_event',
+ - 'figure_leave_event',
+ - 'axes_enter_event',
+ - 'axes_leave_event'
+ - 'close_event'.
+
+ func : callable
+ The callback function to be executed, which must have the
+ signature::
+
+ def func(event: Event) -> Any
+
+ For the location events (button and key press/release), if the
+ mouse is over the Axes, the ``inaxes`` attribute of the event will
+ be set to the `~matplotlib.axes.Axes` the event occurs is over, and
+ additionally, the variables ``xdata`` and ``ydata`` attributes will
+ be set to the mouse location in data coordinates. See `.KeyEvent`
+ and `.MouseEvent` for more info.
+
+ .. note::
+
+ If func is a method, this only stores a weak reference to the
+ method. Thus, the figure does not influence the lifetime of
+ the associated object. Usually, you want to make sure that the
+ object is kept alive throughout the lifetime of the figure by
+ holding a reference to it.
+
+ Returns
+ -------
+ cid
+ A connection id that can be used with
+ `.FigureCanvasBase.mpl_disconnect`.
+
+ Examples
+ --------
+ ::
+
+ def on_press(event):
+ print('you pressed', event.button, event.xdata, event.ydata)
+
+ cid = canvas.mpl_connect('button_press_event', on_press)
+ """
+
+ return self.callbacks.connect(s, func)
+
+ def mpl_disconnect(self, cid):
+ """
+ Disconnect the callback with id *cid*.
+
+ Examples
+ --------
+ ::
+
+ cid = canvas.mpl_connect('button_press_event', on_press)
+ # ... later
+ canvas.mpl_disconnect(cid)
+ """
+ self.callbacks.disconnect(cid)
+
+ # Internal subclasses can override _timer_cls instead of new_timer, though
+ # this is not a public API for third-party subclasses.
+ _timer_cls = TimerBase
+
+ def new_timer(self, interval=None, callbacks=None):
+ """
+ Create a new backend-specific subclass of `.Timer`.
+
+ This is useful for getting periodic events through the backend's native
+ event loop. Implemented only for backends with GUIs.
+
+ Parameters
+ ----------
+ interval : int
+ Timer interval in milliseconds.
+
+ callbacks : list[tuple[callable, tuple, dict]]
+ Sequence of (func, args, kwargs) where ``func(*args, **kwargs)``
+ will be executed by the timer every *interval*.
+
+ Callbacks which return ``False`` or ``0`` will be removed from the
+ timer.
+
+ Examples
+ --------
+ >>> timer = fig.canvas.new_timer(callbacks=[(f1, (1,), {'a': 3})])
+ """
+ return self._timer_cls(interval=interval, callbacks=callbacks)
+
+ def flush_events(self):
+ """
+ Flush the GUI events for the figure.
+
+ Interactive backends need to reimplement this method.
+ """
+
+ def start_event_loop(self, timeout=0):
+ """
+ Start a blocking event loop.
+
+ Such an event loop is used by interactive functions, such as
+ `~.Figure.ginput` and `~.Figure.waitforbuttonpress`, to wait for
+ events.
+
+ The event loop blocks until a callback function triggers
+ `stop_event_loop`, or *timeout* is reached.
+
+ If *timeout* is 0 or negative, never timeout.
+
+ Only interactive backends need to reimplement this method and it relies
+ on `flush_events` being properly implemented.
+
+ Interactive backends should implement this in a more native way.
+ """
+ if timeout <= 0:
+ timeout = np.inf
+ timestep = 0.01
+ counter = 0
+ self._looping = True
+ while self._looping and counter * timestep < timeout:
+ self.flush_events()
+ time.sleep(timestep)
+ counter += 1
+
+ def stop_event_loop(self):
+ """
+ Stop the current blocking event loop.
+
+ Interactive backends need to reimplement this to match
+ `start_event_loop`
+ """
+ self._looping = False
+
+
+def key_press_handler(event, canvas=None, toolbar=None):
+ """
+ Implement the default Matplotlib key bindings for the canvas and toolbar
+ described at :ref:`key-event-handling`.
+
+ Parameters
+ ----------
+ event : `KeyEvent`
+ A key press/release event.
+ canvas : `FigureCanvasBase`, default: ``event.canvas``
+ The backend-specific canvas instance. This parameter is kept for
+ back-compatibility, but, if set, should always be equal to
+ ``event.canvas``.
+ toolbar : `NavigationToolbar2`, default: ``event.canvas.toolbar``
+ The navigation cursor toolbar. This parameter is kept for
+ back-compatibility, but, if set, should always be equal to
+ ``event.canvas.toolbar``.
+ """
+ if event.key is None:
+ return
+ if canvas is None:
+ canvas = event.canvas
+ if toolbar is None:
+ toolbar = canvas.toolbar
+
+ # toggle fullscreen mode (default key 'f', 'ctrl + f')
+ if event.key in rcParams['keymap.fullscreen']:
+ try:
+ canvas.manager.full_screen_toggle()
+ except AttributeError:
+ pass
+
+ # quit the figure (default key 'ctrl+w')
+ if event.key in rcParams['keymap.quit']:
+ Gcf.destroy_fig(canvas.figure)
+ if event.key in rcParams['keymap.quit_all']:
+ Gcf.destroy_all()
+
+ if toolbar is not None:
+ # home or reset mnemonic (default key 'h', 'home' and 'r')
+ if event.key in rcParams['keymap.home']:
+ toolbar.home()
+ # forward / backward keys to enable left handed quick navigation
+ # (default key for backward: 'left', 'backspace' and 'c')
+ elif event.key in rcParams['keymap.back']:
+ toolbar.back()
+ # (default key for forward: 'right' and 'v')
+ elif event.key in rcParams['keymap.forward']:
+ toolbar.forward()
+ # pan mnemonic (default key 'p')
+ elif event.key in rcParams['keymap.pan']:
+ toolbar.pan()
+ toolbar._update_cursor(event)
+ # zoom mnemonic (default key 'o')
+ elif event.key in rcParams['keymap.zoom']:
+ toolbar.zoom()
+ toolbar._update_cursor(event)
+ # saving current figure (default key 's')
+ elif event.key in rcParams['keymap.save']:
+ toolbar.save_figure()
+
+ if event.inaxes is None:
+ return
+
+ # these bindings require the mouse to be over an Axes to trigger
+ def _get_uniform_gridstate(ticks):
+ # Return True/False if all grid lines are on or off, None if they are
+ # not all in the same state.
+ return (True if all(tick.gridline.get_visible() for tick in ticks) else
+ False if not any(tick.gridline.get_visible() for tick in ticks) else
+ None)
+
+ ax = event.inaxes
+ # toggle major grids in current Axes (default key 'g')
+ # Both here and below (for 'G'), we do nothing if *any* grid (major or
+ # minor, x or y) is not in a uniform state, to avoid messing up user
+ # customization.
+ if (event.key in rcParams['keymap.grid']
+ # Exclude minor grids not in a uniform state.
+ and None not in [_get_uniform_gridstate(ax.xaxis.minorTicks),
+ _get_uniform_gridstate(ax.yaxis.minorTicks)]):
+ x_state = _get_uniform_gridstate(ax.xaxis.majorTicks)
+ y_state = _get_uniform_gridstate(ax.yaxis.majorTicks)
+ cycle = [(False, False), (True, False), (True, True), (False, True)]
+ try:
+ x_state, y_state = (
+ cycle[(cycle.index((x_state, y_state)) + 1) % len(cycle)])
+ except ValueError:
+ # Exclude major grids not in a uniform state.
+ pass
+ else:
+ # If turning major grids off, also turn minor grids off.
+ ax.grid(x_state, which="major" if x_state else "both", axis="x")
+ ax.grid(y_state, which="major" if y_state else "both", axis="y")
+ canvas.draw_idle()
+ # toggle major and minor grids in current Axes (default key 'G')
+ if (event.key in rcParams['keymap.grid_minor']
+ # Exclude major grids not in a uniform state.
+ and None not in [_get_uniform_gridstate(ax.xaxis.majorTicks),
+ _get_uniform_gridstate(ax.yaxis.majorTicks)]):
+ x_state = _get_uniform_gridstate(ax.xaxis.minorTicks)
+ y_state = _get_uniform_gridstate(ax.yaxis.minorTicks)
+ cycle = [(False, False), (True, False), (True, True), (False, True)]
+ try:
+ x_state, y_state = (
+ cycle[(cycle.index((x_state, y_state)) + 1) % len(cycle)])
+ except ValueError:
+ # Exclude minor grids not in a uniform state.
+ pass
+ else:
+ ax.grid(x_state, which="both", axis="x")
+ ax.grid(y_state, which="both", axis="y")
+ canvas.draw_idle()
+ # toggle scaling of y-axes between 'log and 'linear' (default key 'l')
+ elif event.key in rcParams['keymap.yscale']:
+ scale = ax.get_yscale()
+ if scale == 'log':
+ ax.set_yscale('linear')
+ ax.get_figure(root=True).canvas.draw_idle()
+ elif scale == 'linear':
+ try:
+ ax.set_yscale('log')
+ except ValueError as exc:
+ _log.warning(str(exc))
+ ax.set_yscale('linear')
+ ax.get_figure(root=True).canvas.draw_idle()
+ # toggle scaling of x-axes between 'log and 'linear' (default key 'k')
+ elif event.key in rcParams['keymap.xscale']:
+ scalex = ax.get_xscale()
+ if scalex == 'log':
+ ax.set_xscale('linear')
+ ax.get_figure(root=True).canvas.draw_idle()
+ elif scalex == 'linear':
+ try:
+ ax.set_xscale('log')
+ except ValueError as exc:
+ _log.warning(str(exc))
+ ax.set_xscale('linear')
+ ax.get_figure(root=True).canvas.draw_idle()
+
+
+def button_press_handler(event, canvas=None, toolbar=None):
+ """
+ The default Matplotlib button actions for extra mouse buttons.
+
+ Parameters are as for `key_press_handler`, except that *event* is a
+ `MouseEvent`.
+ """
+ if canvas is None:
+ canvas = event.canvas
+ if toolbar is None:
+ toolbar = canvas.toolbar
+ if toolbar is not None:
+ button_name = str(MouseButton(event.button))
+ if button_name in rcParams['keymap.back']:
+ toolbar.back()
+ elif button_name in rcParams['keymap.forward']:
+ toolbar.forward()
+
+
+class NonGuiException(Exception):
+ """Raised when trying show a figure in a non-GUI backend."""
+ pass
+
+
+class FigureManagerBase:
+ """
+ A backend-independent abstraction of a figure container and controller.
+
+ The figure manager is used by pyplot to interact with the window in a
+ backend-independent way. It's an adapter for the real (GUI) framework that
+ represents the visual figure on screen.
+
+ The figure manager is connected to a specific canvas instance, which in turn
+ is connected to a specific figure instance. To access a figure manager for
+ a given figure in user code, you typically use ``fig.canvas.manager``.
+
+ GUI backends derive from this class to translate common operations such
+ as *show* or *resize* to the GUI-specific code. Non-GUI backends do not
+ support these operations and can just use the base class.
+
+ This following basic operations are accessible:
+
+ **Window operations**
+
+ - `~.FigureManagerBase.show`
+ - `~.FigureManagerBase.destroy`
+ - `~.FigureManagerBase.full_screen_toggle`
+ - `~.FigureManagerBase.resize`
+ - `~.FigureManagerBase.get_window_title`
+ - `~.FigureManagerBase.set_window_title`
+
+ **Key and mouse button press handling**
+
+ The figure manager sets up default key and mouse button press handling by
+ hooking up the `.key_press_handler` to the matplotlib event system. This
+ ensures the same shortcuts and mouse actions across backends.
+
+ **Other operations**
+
+ Subclasses will have additional attributes and functions to access
+ additional functionality. This is of course backend-specific. For example,
+ most GUI backends have ``window`` and ``toolbar`` attributes that give
+ access to the native GUI widgets of the respective framework.
+
+ Attributes
+ ----------
+ canvas : `FigureCanvasBase`
+ The backend-specific canvas instance.
+
+ num : int or str
+ The figure number.
+
+ key_press_handler_id : int
+ The default key handler cid, when using the toolmanager.
+ To disable the default key press handling use::
+
+ figure.canvas.mpl_disconnect(
+ figure.canvas.manager.key_press_handler_id)
+
+ button_press_handler_id : int
+ The default mouse button handler cid, when using the toolmanager.
+ To disable the default button press handling use::
+
+ figure.canvas.mpl_disconnect(
+ figure.canvas.manager.button_press_handler_id)
+ """
+
+ _toolbar2_class = None
+ _toolmanager_toolbar_class = None
+
+ def __init__(self, canvas, num):
+ self.canvas = canvas
+ canvas.manager = self # store a pointer to parent
+ self.num = num
+ self.set_window_title(f"Figure {num:d}")
+
+ self.key_press_handler_id = None
+ self.button_press_handler_id = None
+ if rcParams['toolbar'] != 'toolmanager':
+ self.key_press_handler_id = self.canvas.mpl_connect(
+ 'key_press_event', key_press_handler)
+ self.button_press_handler_id = self.canvas.mpl_connect(
+ 'button_press_event', button_press_handler)
+
+ self.toolmanager = (ToolManager(canvas.figure)
+ if mpl.rcParams['toolbar'] == 'toolmanager'
+ else None)
+ if (mpl.rcParams["toolbar"] == "toolbar2"
+ and self._toolbar2_class):
+ self.toolbar = self._toolbar2_class(self.canvas)
+ elif (mpl.rcParams["toolbar"] == "toolmanager"
+ and self._toolmanager_toolbar_class):
+ self.toolbar = self._toolmanager_toolbar_class(self.toolmanager)
+ else:
+ self.toolbar = None
+
+ if self.toolmanager:
+ tools.add_tools_to_manager(self.toolmanager)
+ if self.toolbar:
+ tools.add_tools_to_container(self.toolbar)
+
+ @self.canvas.figure.add_axobserver
+ def notify_axes_change(fig):
+ # Called whenever the current Axes is changed.
+ if self.toolmanager is None and self.toolbar is not None:
+ self.toolbar.update()
+
+ @classmethod
+ def create_with_canvas(cls, canvas_class, figure, num):
+ """
+ Create a manager for a given *figure* using a specific *canvas_class*.
+
+ Backends should override this method if they have specific needs for
+ setting up the canvas or the manager.
+ """
+ return cls(canvas_class(figure), num)
+
+ @classmethod
+ def start_main_loop(cls):
+ """
+ Start the main event loop.
+
+ This method is called by `.FigureManagerBase.pyplot_show`, which is the
+ implementation of `.pyplot.show`. To customize the behavior of
+ `.pyplot.show`, interactive backends should usually override
+ `~.FigureManagerBase.start_main_loop`; if more customized logic is
+ necessary, `~.FigureManagerBase.pyplot_show` can also be overridden.
+ """
+
+ @classmethod
+ def pyplot_show(cls, *, block=None):
+ """
+ Show all figures. This method is the implementation of `.pyplot.show`.
+
+ To customize the behavior of `.pyplot.show`, interactive backends
+ should usually override `~.FigureManagerBase.start_main_loop`; if more
+ customized logic is necessary, `~.FigureManagerBase.pyplot_show` can
+ also be overridden.
+
+ Parameters
+ ----------
+ block : bool, optional
+ Whether to block by calling ``start_main_loop``. The default,
+ None, means to block if we are neither in IPython's ``%pylab`` mode
+ nor in ``interactive`` mode.
+ """
+ managers = Gcf.get_all_fig_managers()
+ if not managers:
+ return
+ for manager in managers:
+ try:
+ manager.show() # Emits a warning for non-interactive backend.
+ except NonGuiException as exc:
+ _api.warn_external(str(exc))
+ if block is None:
+ # Hack: Are we in IPython's %pylab mode? In pylab mode, IPython
+ # (>= 0.10) tacks a _needmain attribute onto pyplot.show (always
+ # set to False).
+ pyplot_show = getattr(sys.modules.get("matplotlib.pyplot"), "show", None)
+ ipython_pylab = hasattr(pyplot_show, "_needmain")
+ block = not ipython_pylab and not is_interactive()
+ if block:
+ cls.start_main_loop()
+
+ def show(self):
+ """
+ For GUI backends, show the figure window and redraw.
+ For non-GUI backends, raise an exception, unless running headless (i.e.
+ on Linux with an unset DISPLAY); this exception is converted to a
+ warning in `.Figure.show`.
+ """
+ # This should be overridden in GUI backends.
+ if sys.platform == "linux" and not os.environ.get("DISPLAY"):
+ # We cannot check _get_running_interactive_framework() ==
+ # "headless" because that would also suppress the warning when
+ # $DISPLAY exists but is invalid, which is more likely an error and
+ # thus warrants a warning.
+ return
+ raise NonGuiException(
+ f"{type(self.canvas).__name__} is non-interactive, and thus cannot be "
+ f"shown")
+
+ def destroy(self):
+ pass
+
+ def full_screen_toggle(self):
+ pass
+
+ def resize(self, w, h):
+ """For GUI backends, resize the window (in physical pixels)."""
+
+ def get_window_title(self):
+ """Return the title text of the window containing the figure."""
+ return self._window_title
+
+ def set_window_title(self, title):
+ """
+ Set the title text of the window containing the figure.
+
+ Examples
+ --------
+ >>> fig = plt.figure()
+ >>> fig.canvas.manager.set_window_title('My figure')
+ """
+ # This attribute is not defined in __init__ (but __init__ calls this
+ # setter), as derived classes (real GUI managers) will store this
+ # information directly on the widget; only the base (non-GUI) manager
+ # class needs a specific attribute for it (so that filename escaping
+ # can be checked in the test suite).
+ self._window_title = title
+
+
+cursors = tools.cursors
+
+
+class _Mode(str, Enum):
+ NONE = ""
+ PAN = "pan/zoom"
+ ZOOM = "zoom rect"
+
+ def __str__(self):
+ return self.value
+
+ @property
+ def _navigate_mode(self):
+ return self.name if self is not _Mode.NONE else None
+
+
+class NavigationToolbar2:
+ """
+ Base class for the navigation cursor, version 2.
+
+ Backends must implement a canvas that handles connections for
+ 'button_press_event' and 'button_release_event'. See
+ :meth:`FigureCanvasBase.mpl_connect` for more information.
+
+ They must also define
+
+ :meth:`save_figure`
+ Save the current figure.
+
+ :meth:`draw_rubberband` (optional)
+ Draw the zoom to rect "rubberband" rectangle.
+
+ :meth:`set_message` (optional)
+ Display message.
+
+ :meth:`set_history_buttons` (optional)
+ You can change the history back / forward buttons to indicate disabled / enabled
+ state.
+
+ and override ``__init__`` to set up the toolbar -- without forgetting to
+ call the base-class init. Typically, ``__init__`` needs to set up toolbar
+ buttons connected to the `home`, `back`, `forward`, `pan`, `zoom`, and
+ `save_figure` methods and using standard icons in the "images" subdirectory
+ of the data path.
+
+ That's it, we'll do the rest!
+ """
+
+ # list of toolitems to add to the toolbar, format is:
+ # (
+ # text, # the text of the button (often not visible to users)
+ # tooltip_text, # the tooltip shown on hover (where possible)
+ # image_file, # name of the image for the button (without the extension)
+ # name_of_method, # name of the method in NavigationToolbar2 to call
+ # )
+ toolitems = (
+ ('Home', 'Reset original view', 'home', 'home'),
+ ('Back', 'Back to previous view', 'back', 'back'),
+ ('Forward', 'Forward to next view', 'forward', 'forward'),
+ (None, None, None, None),
+ ('Pan',
+ 'Left button pans, Right button zooms\n'
+ 'x/y fixes axis, CTRL fixes aspect',
+ 'move', 'pan'),
+ ('Zoom', 'Zoom to rectangle\nx/y fixes axis', 'zoom_to_rect', 'zoom'),
+ ('Subplots', 'Configure subplots', 'subplots', 'configure_subplots'),
+ (None, None, None, None),
+ ('Save', 'Save the figure', 'filesave', 'save_figure'),
+ )
+
+ UNKNOWN_SAVED_STATUS = object()
+
+ def __init__(self, canvas):
+ self.canvas = canvas
+ canvas.toolbar = self
+ self._nav_stack = cbook._Stack()
+ # This cursor will be set after the initial draw.
+ self._last_cursor = tools.Cursors.POINTER
+
+ self._id_press = self.canvas.mpl_connect(
+ 'button_press_event', self._zoom_pan_handler)
+ self._id_release = self.canvas.mpl_connect(
+ 'button_release_event', self._zoom_pan_handler)
+ self._id_drag = self.canvas.mpl_connect(
+ 'motion_notify_event', self.mouse_move)
+ self._pan_info = None
+ self._zoom_info = None
+
+ self.mode = _Mode.NONE # a mode string for the status bar
+ self.set_history_buttons()
+
+ def set_message(self, s):
+ """Display a message on toolbar or in status bar."""
+
+ def draw_rubberband(self, event, x0, y0, x1, y1):
+ """
+ Draw a rectangle rubberband to indicate zoom limits.
+
+ Note that it is not guaranteed that ``x0 <= x1`` and ``y0 <= y1``.
+ """
+
+ def remove_rubberband(self):
+ """Remove the rubberband."""
+
+ def home(self, *args):
+ """
+ Restore the original view.
+
+ For convenience of being directly connected as a GUI callback, which
+ often get passed additional parameters, this method accepts arbitrary
+ parameters, but does not use them.
+ """
+ self._nav_stack.home()
+ self.set_history_buttons()
+ self._update_view()
+
+ def back(self, *args):
+ """
+ Move back up the view lim stack.
+
+ For convenience of being directly connected as a GUI callback, which
+ often get passed additional parameters, this method accepts arbitrary
+ parameters, but does not use them.
+ """
+ self._nav_stack.back()
+ self.set_history_buttons()
+ self._update_view()
+
+ def forward(self, *args):
+ """
+ Move forward in the view lim stack.
+
+ For convenience of being directly connected as a GUI callback, which
+ often get passed additional parameters, this method accepts arbitrary
+ parameters, but does not use them.
+ """
+ self._nav_stack.forward()
+ self.set_history_buttons()
+ self._update_view()
+
+ def _update_cursor(self, event):
+ """
+ Update the cursor after a mouse move event or a tool (de)activation.
+ """
+ if self.mode and event.inaxes and event.inaxes.get_navigate():
+ if (self.mode == _Mode.ZOOM
+ and self._last_cursor != tools.Cursors.SELECT_REGION):
+ self.canvas.set_cursor(tools.Cursors.SELECT_REGION)
+ self._last_cursor = tools.Cursors.SELECT_REGION
+ elif (self.mode == _Mode.PAN
+ and self._last_cursor != tools.Cursors.MOVE):
+ self.canvas.set_cursor(tools.Cursors.MOVE)
+ self._last_cursor = tools.Cursors.MOVE
+ elif self._last_cursor != tools.Cursors.POINTER:
+ self.canvas.set_cursor(tools.Cursors.POINTER)
+ self._last_cursor = tools.Cursors.POINTER
+
+ @contextmanager
+ def _wait_cursor_for_draw_cm(self):
+ """
+ Set the cursor to a wait cursor when drawing the canvas.
+
+ In order to avoid constantly changing the cursor when the canvas
+ changes frequently, do nothing if this context was triggered during the
+ last second. (Optimally we'd prefer only setting the wait cursor if
+ the *current* draw takes too long, but the current draw blocks the GUI
+ thread).
+ """
+ self._draw_time, last_draw_time = (
+ time.time(), getattr(self, "_draw_time", -np.inf))
+ if self._draw_time - last_draw_time > 1:
+ try:
+ self.canvas.set_cursor(tools.Cursors.WAIT)
+ yield
+ finally:
+ self.canvas.set_cursor(self._last_cursor)
+ else:
+ yield
+
+ @staticmethod
+ def _mouse_event_to_message(event):
+ if event.inaxes and event.inaxes.get_navigate():
+ try:
+ s = event.inaxes.format_coord(event.xdata, event.ydata)
+ except (ValueError, OverflowError):
+ pass
+ else:
+ s = s.rstrip()
+ artists = [a for a in event.inaxes._mouseover_set
+ if a.contains(event)[0] and a.get_visible()]
+ if artists:
+ a = cbook._topmost_artist(artists)
+ if a is not event.inaxes.patch:
+ data = a.get_cursor_data(event)
+ if data is not None:
+ data_str = a.format_cursor_data(data).rstrip()
+ if data_str:
+ s = s + '\n' + data_str
+ return s
+ return ""
+
+ def mouse_move(self, event):
+ self._update_cursor(event)
+ self.set_message(self._mouse_event_to_message(event))
+
+ def _zoom_pan_handler(self, event):
+ if self.mode == _Mode.PAN:
+ if event.name == "button_press_event":
+ self.press_pan(event)
+ elif event.name == "button_release_event":
+ self.release_pan(event)
+ if self.mode == _Mode.ZOOM:
+ if event.name == "button_press_event":
+ self.press_zoom(event)
+ elif event.name == "button_release_event":
+ self.release_zoom(event)
+
+ def _start_event_axes_interaction(self, event, *, method):
+
+ def _ax_filter(ax):
+ return (ax.in_axes(event) and
+ ax.get_navigate() and
+ getattr(ax, f"can_{method}")()
+ )
+
+ def _capture_events(ax):
+ f = ax.get_forward_navigation_events()
+ if f == "auto": # (capture = patch visibility)
+ f = not ax.patch.get_visible()
+ return not f
+
+ # get all relevant axes for the event
+ axes = list(filter(_ax_filter, self.canvas.figure.get_axes()))
+
+ if len(axes) == 0:
+ return []
+
+ if self._nav_stack() is None:
+ self.push_current() # Set the home button to this view.
+
+ # group axes by zorder (reverse to trigger later axes first)
+ grps = dict()
+ for ax in reversed(axes):
+ grps.setdefault(ax.get_zorder(), []).append(ax)
+
+ axes_to_trigger = []
+ # go through zorders in reverse until we hit a capturing axes
+ for zorder in sorted(grps, reverse=True):
+ for ax in grps[zorder]:
+ axes_to_trigger.append(ax)
+ # NOTE: shared axes are automatically triggered, but twin-axes not!
+ axes_to_trigger.extend(ax._twinned_axes.get_siblings(ax))
+
+ if _capture_events(ax):
+ break # break if we hit a capturing axes
+ else:
+ # If the inner loop finished without an explicit break,
+ # (e.g. no capturing axes was found) continue the
+ # outer loop to the next zorder.
+ continue
+
+ # If the inner loop was terminated with an explicit break,
+ # terminate the outer loop as well.
+ break
+
+ # avoid duplicated triggers (but keep order of list)
+ axes_to_trigger = list(dict.fromkeys(axes_to_trigger))
+
+ return axes_to_trigger
+
+ def pan(self, *args):
+ """
+ Toggle the pan/zoom tool.
+
+ Pan with left button, zoom with right.
+ """
+ if not self.canvas.widgetlock.available(self):
+ self.set_message("pan unavailable")
+ return
+ if self.mode == _Mode.PAN:
+ self.mode = _Mode.NONE
+ self.canvas.widgetlock.release(self)
+ else:
+ self.mode = _Mode.PAN
+ self.canvas.widgetlock(self)
+ for a in self.canvas.figure.get_axes():
+ a.set_navigate_mode(self.mode._navigate_mode)
+
+ _PanInfo = namedtuple("_PanInfo", "button axes cid")
+
+ def press_pan(self, event):
+ """Callback for mouse button press in pan/zoom mode."""
+ if (event.button not in [MouseButton.LEFT, MouseButton.RIGHT]
+ or event.x is None or event.y is None):
+ return
+
+ axes = self._start_event_axes_interaction(event, method="pan")
+ if not axes:
+ return
+
+ # call "ax.start_pan(..)" on all relevant axes of an event
+ for ax in axes:
+ ax.start_pan(event.x, event.y, event.button)
+
+ self.canvas.mpl_disconnect(self._id_drag)
+ id_drag = self.canvas.mpl_connect("motion_notify_event", self.drag_pan)
+
+ self._pan_info = self._PanInfo(
+ button=event.button, axes=axes, cid=id_drag)
+
+ def drag_pan(self, event):
+ """Callback for dragging in pan/zoom mode."""
+ for ax in self._pan_info.axes:
+ # Using the recorded button at the press is safer than the current
+ # button, as multiple buttons can get pressed during motion.
+ ax.drag_pan(self._pan_info.button, event.key, event.x, event.y)
+ self.canvas.draw_idle()
+
+ def release_pan(self, event):
+ """Callback for mouse button release in pan/zoom mode."""
+ if self._pan_info is None:
+ return
+ self.canvas.mpl_disconnect(self._pan_info.cid)
+ self._id_drag = self.canvas.mpl_connect(
+ 'motion_notify_event', self.mouse_move)
+ for ax in self._pan_info.axes:
+ ax.end_pan()
+ self.canvas.draw_idle()
+ self._pan_info = None
+ self.push_current()
+
+ def zoom(self, *args):
+ if not self.canvas.widgetlock.available(self):
+ self.set_message("zoom unavailable")
+ return
+ """Toggle zoom to rect mode."""
+ if self.mode == _Mode.ZOOM:
+ self.mode = _Mode.NONE
+ self.canvas.widgetlock.release(self)
+ else:
+ self.mode = _Mode.ZOOM
+ self.canvas.widgetlock(self)
+ for a in self.canvas.figure.get_axes():
+ a.set_navigate_mode(self.mode._navigate_mode)
+
+ _ZoomInfo = namedtuple("_ZoomInfo", "direction start_xy axes cid cbar")
+
+ def press_zoom(self, event):
+ """Callback for mouse button press in zoom to rect mode."""
+ if (event.button not in [MouseButton.LEFT, MouseButton.RIGHT]
+ or event.x is None or event.y is None):
+ return
+
+ axes = self._start_event_axes_interaction(event, method="zoom")
+ if not axes:
+ return
+
+ id_zoom = self.canvas.mpl_connect(
+ "motion_notify_event", self.drag_zoom)
+
+ # A colorbar is one-dimensional, so we extend the zoom rectangle out
+ # to the edge of the Axes bbox in the other dimension. To do that we
+ # store the orientation of the colorbar for later.
+ parent_ax = axes[0]
+ if hasattr(parent_ax, "_colorbar"):
+ cbar = parent_ax._colorbar.orientation
+ else:
+ cbar = None
+
+ self._zoom_info = self._ZoomInfo(
+ direction="in" if event.button == 1 else "out",
+ start_xy=(event.x, event.y), axes=axes, cid=id_zoom, cbar=cbar)
+
+ def drag_zoom(self, event):
+ """Callback for dragging in zoom mode."""
+ start_xy = self._zoom_info.start_xy
+ ax = self._zoom_info.axes[0]
+ (x1, y1), (x2, y2) = np.clip(
+ [start_xy, [event.x, event.y]], ax.bbox.min, ax.bbox.max)
+ key = event.key
+ # Force the key on colorbars to extend the short-axis bbox
+ if self._zoom_info.cbar == "horizontal":
+ key = "x"
+ elif self._zoom_info.cbar == "vertical":
+ key = "y"
+ if key == "x":
+ y1, y2 = ax.bbox.intervaly
+ elif key == "y":
+ x1, x2 = ax.bbox.intervalx
+
+ self.draw_rubberband(event, x1, y1, x2, y2)
+
+ def release_zoom(self, event):
+ """Callback for mouse button release in zoom to rect mode."""
+ if self._zoom_info is None:
+ return
+
+ # We don't check the event button here, so that zooms can be cancelled
+ # by (pressing and) releasing another mouse button.
+ self.canvas.mpl_disconnect(self._zoom_info.cid)
+ self.remove_rubberband()
+
+ start_x, start_y = self._zoom_info.start_xy
+ key = event.key
+ # Force the key on colorbars to ignore the zoom-cancel on the
+ # short-axis side
+ if self._zoom_info.cbar == "horizontal":
+ key = "x"
+ elif self._zoom_info.cbar == "vertical":
+ key = "y"
+ # Ignore single clicks: 5 pixels is a threshold that allows the user to
+ # "cancel" a zoom action by zooming by less than 5 pixels.
+ if ((abs(event.x - start_x) < 5 and key != "y") or
+ (abs(event.y - start_y) < 5 and key != "x")):
+ self.canvas.draw_idle()
+ self._zoom_info = None
+ return
+
+ for i, ax in enumerate(self._zoom_info.axes):
+ # Detect whether this Axes is twinned with an earlier Axes in the
+ # list of zoomed Axes, to avoid double zooming.
+ twinx = any(ax.get_shared_x_axes().joined(ax, prev)
+ for prev in self._zoom_info.axes[:i])
+ twiny = any(ax.get_shared_y_axes().joined(ax, prev)
+ for prev in self._zoom_info.axes[:i])
+ ax._set_view_from_bbox(
+ (start_x, start_y, event.x, event.y),
+ self._zoom_info.direction, key, twinx, twiny)
+
+ self.canvas.draw_idle()
+ self._zoom_info = None
+ self.push_current()
+
+ def push_current(self):
+ """Push the current view limits and position onto the stack."""
+ self._nav_stack.push(
+ WeakKeyDictionary(
+ {ax: (ax._get_view(),
+ # Store both the original and modified positions.
+ (ax.get_position(True).frozen(),
+ ax.get_position().frozen()))
+ for ax in self.canvas.figure.axes}))
+ self.set_history_buttons()
+
+ def _update_view(self):
+ """
+ Update the viewlim and position from the view and position stack for
+ each Axes.
+ """
+ nav_info = self._nav_stack()
+ if nav_info is None:
+ return
+ # Retrieve all items at once to avoid any risk of GC deleting an Axes
+ # while in the middle of the loop below.
+ items = list(nav_info.items())
+ for ax, (view, (pos_orig, pos_active)) in items:
+ ax._set_view(view)
+ # Restore both the original and modified positions
+ ax._set_position(pos_orig, 'original')
+ ax._set_position(pos_active, 'active')
+ self.canvas.draw_idle()
+
+ def configure_subplots(self, *args):
+ if hasattr(self, "subplot_tool"):
+ self.subplot_tool.figure.canvas.manager.show()
+ return
+ # This import needs to happen here due to circular imports.
+ from matplotlib.figure import Figure
+ with mpl.rc_context({"toolbar": "none"}): # No navbar for the toolfig.
+ manager = type(self.canvas).new_manager(Figure(figsize=(6, 3)), -1)
+ manager.set_window_title("Subplot configuration tool")
+ tool_fig = manager.canvas.figure
+ tool_fig.subplots_adjust(top=0.9)
+ self.subplot_tool = widgets.SubplotTool(self.canvas.figure, tool_fig)
+ cid = self.canvas.mpl_connect(
+ "close_event", lambda e: manager.destroy())
+
+ def on_tool_fig_close(e):
+ self.canvas.mpl_disconnect(cid)
+ del self.subplot_tool
+
+ tool_fig.canvas.mpl_connect("close_event", on_tool_fig_close)
+ manager.show()
+ return self.subplot_tool
+
+ def save_figure(self, *args):
+ """
+ Save the current figure.
+
+ Backend implementations may choose to return
+ the absolute path of the saved file, if any, as
+ a string.
+
+ If no file is created then `None` is returned.
+
+ If the backend does not implement this functionality
+ then `NavigationToolbar2.UNKNOWN_SAVED_STATUS` is returned.
+
+ Returns
+ -------
+ str or `NavigationToolbar2.UNKNOWN_SAVED_STATUS` or `None`
+ The filepath of the saved figure.
+ Returns `None` if figure is not saved.
+ Returns `NavigationToolbar2.UNKNOWN_SAVED_STATUS` when
+ the backend does not provide the information.
+ """
+ raise NotImplementedError
+
+ def update(self):
+ """Reset the Axes stack."""
+ self._nav_stack.clear()
+ self.set_history_buttons()
+
+ def set_history_buttons(self):
+ """Enable or disable the back/forward button."""
+
+
+class ToolContainerBase:
+ """
+ Base class for all tool containers, e.g. toolbars.
+
+ Attributes
+ ----------
+ toolmanager : `.ToolManager`
+ The tools with which this `ToolContainer` wants to communicate.
+ """
+
+ _icon_extension = '.png'
+ """
+ Toolcontainer button icon image format extension
+
+ **String**: Image extension
+ """
+
+ def __init__(self, toolmanager):
+ self.toolmanager = toolmanager
+ toolmanager.toolmanager_connect(
+ 'tool_message_event',
+ lambda event: self.set_message(event.message))
+ toolmanager.toolmanager_connect(
+ 'tool_removed_event',
+ lambda event: self.remove_toolitem(event.tool.name))
+
+ def _tool_toggled_cbk(self, event):
+ """
+ Capture the 'tool_trigger_[name]'
+
+ This only gets used for toggled tools.
+ """
+ self.toggle_toolitem(event.tool.name, event.tool.toggled)
+
+ def add_tool(self, tool, group, position=-1):
+ """
+ Add a tool to this container.
+
+ Parameters
+ ----------
+ tool : tool_like
+ The tool to add, see `.ToolManager.get_tool`.
+ group : str
+ The name of the group to add this tool to.
+ position : int, default: -1
+ The position within the group to place this tool.
+ """
+ tool = self.toolmanager.get_tool(tool)
+ image = self._get_image_filename(tool)
+ toggle = getattr(tool, 'toggled', None) is not None
+ self.add_toolitem(tool.name, group, position,
+ image, tool.description, toggle)
+ if toggle:
+ self.toolmanager.toolmanager_connect('tool_trigger_%s' % tool.name,
+ self._tool_toggled_cbk)
+ # If initially toggled
+ if tool.toggled:
+ self.toggle_toolitem(tool.name, True)
+
+ def _get_image_filename(self, tool):
+ """Resolve a tool icon's filename."""
+ if not tool.image:
+ return None
+ if os.path.isabs(tool.image):
+ filename = tool.image
+ else:
+ if "image" in getattr(tool, "__dict__", {}):
+ raise ValueError("If 'tool.image' is an instance variable, "
+ "it must be an absolute path")
+ for cls in type(tool).__mro__:
+ if "image" in vars(cls):
+ try:
+ src = inspect.getfile(cls)
+ break
+ except (OSError, TypeError):
+ raise ValueError("Failed to locate source file "
+ "where 'tool.image' is defined") from None
+ else:
+ raise ValueError("Failed to find parent class defining 'tool.image'")
+ filename = str(pathlib.Path(src).parent / tool.image)
+ for filename in [filename, filename + self._icon_extension]:
+ if os.path.isfile(filename):
+ return os.path.abspath(filename)
+ for fname in [ # Fallback; once deprecation elapses.
+ tool.image,
+ tool.image + self._icon_extension,
+ cbook._get_data_path("images", tool.image),
+ cbook._get_data_path("images", tool.image + self._icon_extension),
+ ]:
+ if os.path.isfile(fname):
+ _api.warn_deprecated(
+ "3.9", message=f"Loading icon {tool.image!r} from the current "
+ "directory or from Matplotlib's image directory. This behavior "
+ "is deprecated since %(since)s and will be removed in %(removal)s; "
+ "Tool.image should be set to a path relative to the Tool's source "
+ "file, or to an absolute path.")
+ return os.path.abspath(fname)
+
+ def trigger_tool(self, name):
+ """
+ Trigger the tool.
+
+ Parameters
+ ----------
+ name : str
+ Name (id) of the tool triggered from within the container.
+ """
+ self.toolmanager.trigger_tool(name, sender=self)
+
+ def add_toolitem(self, name, group, position, image, description, toggle):
+ """
+ A hook to add a toolitem to the container.
+
+ This hook must be implemented in each backend and contains the
+ backend-specific code to add an element to the toolbar.
+
+ .. warning::
+ This is part of the backend implementation and should
+ not be called by end-users. They should instead call
+ `.ToolContainerBase.add_tool`.
+
+ The callback associated with the button click event
+ must be *exactly* ``self.trigger_tool(name)``.
+
+ Parameters
+ ----------
+ name : str
+ Name of the tool to add, this gets used as the tool's ID and as the
+ default label of the buttons.
+ group : str
+ Name of the group that this tool belongs to.
+ position : int
+ Position of the tool within its group, if -1 it goes at the end.
+ image : str
+ Filename of the image for the button or `None`.
+ description : str
+ Description of the tool, used for the tooltips.
+ toggle : bool
+ * `True` : The button is a toggle (change the pressed/unpressed
+ state between consecutive clicks).
+ * `False` : The button is a normal button (returns to unpressed
+ state after release).
+ """
+ raise NotImplementedError
+
+ def toggle_toolitem(self, name, toggled):
+ """
+ A hook to toggle a toolitem without firing an event.
+
+ This hook must be implemented in each backend and contains the
+ backend-specific code to silently toggle a toolbar element.
+
+ .. warning::
+ This is part of the backend implementation and should
+ not be called by end-users. They should instead call
+ `.ToolManager.trigger_tool` or `.ToolContainerBase.trigger_tool`
+ (which are equivalent).
+
+ Parameters
+ ----------
+ name : str
+ Id of the tool to toggle.
+ toggled : bool
+ Whether to set this tool as toggled or not.
+ """
+ raise NotImplementedError
+
+ def remove_toolitem(self, name):
+ """
+ A hook to remove a toolitem from the container.
+
+ This hook must be implemented in each backend and contains the
+ backend-specific code to remove an element from the toolbar; it is
+ called when `.ToolManager` emits a ``tool_removed_event``.
+
+ Because some tools are present only on the `.ToolManager` but not on
+ the `ToolContainer`, this method must be a no-op when called on a tool
+ absent from the container.
+
+ .. warning::
+ This is part of the backend implementation and should
+ not be called by end-users. They should instead call
+ `.ToolManager.remove_tool`.
+
+ Parameters
+ ----------
+ name : str
+ Name of the tool to remove.
+ """
+ raise NotImplementedError
+
+ def set_message(self, s):
+ """
+ Display a message on the toolbar.
+
+ Parameters
+ ----------
+ s : str
+ Message text.
+ """
+ raise NotImplementedError
+
+
+class _Backend:
+ # A backend can be defined by using the following pattern:
+ #
+ # @_Backend.export
+ # class FooBackend(_Backend):
+ # # override the attributes and methods documented below.
+
+ # `backend_version` may be overridden by the subclass.
+ backend_version = "unknown"
+
+ # The `FigureCanvas` class must be defined.
+ FigureCanvas = None
+
+ # For interactive backends, the `FigureManager` class must be overridden.
+ FigureManager = FigureManagerBase
+
+ # For interactive backends, `mainloop` should be a function taking no
+ # argument and starting the backend main loop. It should be left as None
+ # for non-interactive backends.
+ mainloop = None
+
+ # The following methods will be automatically defined and exported, but
+ # can be overridden.
+
+ @classmethod
+ def new_figure_manager(cls, num, *args, **kwargs):
+ """Create a new figure manager instance."""
+ # This import needs to happen here due to circular imports.
+ from matplotlib.figure import Figure
+ fig_cls = kwargs.pop('FigureClass', Figure)
+ fig = fig_cls(*args, **kwargs)
+ return cls.new_figure_manager_given_figure(num, fig)
+
+ @classmethod
+ def new_figure_manager_given_figure(cls, num, figure):
+ """Create a new figure manager instance for the given figure."""
+ return cls.FigureCanvas.new_manager(figure, num)
+
+ @classmethod
+ def draw_if_interactive(cls):
+ manager_class = cls.FigureCanvas.manager_class
+ # Interactive backends reimplement start_main_loop or pyplot_show.
+ backend_is_interactive = (
+ manager_class.start_main_loop != FigureManagerBase.start_main_loop
+ or manager_class.pyplot_show != FigureManagerBase.pyplot_show)
+ if backend_is_interactive and is_interactive():
+ manager = Gcf.get_active()
+ if manager:
+ manager.canvas.draw_idle()
+
+ @classmethod
+ def show(cls, *, block=None):
+ """
+ Show all figures.
+
+ `show` blocks by calling `mainloop` if *block* is ``True``, or if it is
+ ``None`` and we are not in `interactive` mode and if IPython's
+ ``%matplotlib`` integration has not been activated.
+ """
+ managers = Gcf.get_all_fig_managers()
+ if not managers:
+ return
+ for manager in managers:
+ try:
+ manager.show() # Emits a warning for non-interactive backend.
+ except NonGuiException as exc:
+ _api.warn_external(str(exc))
+ if cls.mainloop is None:
+ return
+ if block is None:
+ # Hack: Is IPython's %matplotlib integration activated? If so,
+ # IPython's activate_matplotlib (>= 0.10) tacks a _needmain
+ # attribute onto pyplot.show (always set to False).
+ pyplot_show = getattr(sys.modules.get("matplotlib.pyplot"), "show", None)
+ ipython_pylab = hasattr(pyplot_show, "_needmain")
+ block = not ipython_pylab and not is_interactive()
+ if block:
+ cls.mainloop()
+
+ # This method is the one actually exporting the required methods.
+
+ @staticmethod
+ def export(cls):
+ for name in [
+ "backend_version",
+ "FigureCanvas",
+ "FigureManager",
+ "new_figure_manager",
+ "new_figure_manager_given_figure",
+ "draw_if_interactive",
+ "show",
+ ]:
+ setattr(sys.modules[cls.__module__], name, getattr(cls, name))
+
+ # For back-compatibility, generate a shim `Show` class.
+
+ class Show(ShowBase):
+ def mainloop(self):
+ return cls.mainloop()
+
+ setattr(sys.modules[cls.__module__], "Show", Show)
+ return cls
+
+
+class ShowBase(_Backend):
+ """
+ Simple base class to generate a ``show()`` function in backends.
+
+ Subclass must override ``mainloop()`` method.
+ """
+
+ def __call__(self, block=None):
+ return self.show(block=block)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/backend_bases.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/backend_bases.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..23a19b79d3be43f707ff02cf33540aa1102e06cc
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/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/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/backend_managers.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/backend_managers.py
new file mode 100644
index 0000000000000000000000000000000000000000..76f15030bcc5e2c112b9aa72ca9cbf18334599e2
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/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/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/backend_managers.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/backend_managers.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..9e59acb14eda98b25e2dcb3f6e2004ca99d0ae5e
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/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/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/backend_tools.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/backend_tools.py
new file mode 100644
index 0000000000000000000000000000000000000000..87ed794022a0eee732da01ac9627b84020c83013
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/backend_tools.py
@@ -0,0 +1,998 @@
+"""
+Abstract base classes define the primitives for Tools.
+These tools are used by `matplotlib.backend_managers.ToolManager`
+
+:class:`ToolBase`
+ Simple stateless tool
+
+:class:`ToolToggleBase`
+ Tool that has two states, only one Toggle tool can be
+ active at any given time for the same
+ `matplotlib.backend_managers.ToolManager`
+"""
+
+import enum
+import functools
+import re
+import time
+from types import SimpleNamespace
+import uuid
+from weakref import WeakKeyDictionary
+
+import numpy as np
+
+import matplotlib as mpl
+from matplotlib._pylab_helpers import Gcf
+from matplotlib import _api, cbook
+
+
+class Cursors(enum.IntEnum): # Must subclass int for the macOS backend.
+ """Backend-independent cursor types."""
+ POINTER = enum.auto()
+ HAND = enum.auto()
+ SELECT_REGION = enum.auto()
+ MOVE = enum.auto()
+ WAIT = enum.auto()
+ RESIZE_HORIZONTAL = enum.auto()
+ RESIZE_VERTICAL = enum.auto()
+cursors = Cursors # Backcompat.
+
+
+# _tool_registry, _register_tool_class, and _find_tool_class implement a
+# mechanism through which ToolManager.add_tool can determine whether a subclass
+# of the requested tool class has been registered (either for the current
+# canvas class or for a parent class), in which case that tool subclass will be
+# instantiated instead. This is the mechanism used e.g. to allow different
+# GUI backends to implement different specializations for ConfigureSubplots.
+
+
+_tool_registry = set()
+
+
+def _register_tool_class(canvas_cls, tool_cls=None):
+ """Decorator registering *tool_cls* as a tool class for *canvas_cls*."""
+ if tool_cls is None:
+ return functools.partial(_register_tool_class, canvas_cls)
+ _tool_registry.add((canvas_cls, tool_cls))
+ return tool_cls
+
+
+def _find_tool_class(canvas_cls, tool_cls):
+ """Find a subclass of *tool_cls* registered for *canvas_cls*."""
+ for canvas_parent in canvas_cls.__mro__:
+ for tool_child in _api.recursive_subclasses(tool_cls):
+ if (canvas_parent, tool_child) in _tool_registry:
+ return tool_child
+ return tool_cls
+
+
+# Views positions tool
+_views_positions = 'viewpos'
+
+
+class ToolBase:
+ """
+ Base tool class.
+
+ A base tool, only implements `trigger` method or no method at all.
+ The tool is instantiated by `matplotlib.backend_managers.ToolManager`.
+ """
+
+ default_keymap = None
+ """
+ Keymap to associate with this tool.
+
+ ``list[str]``: List of keys that will trigger this tool when a keypress
+ event is emitted on ``self.figure.canvas``. Note that this attribute is
+ looked up on the instance, and can therefore be a property (this is used
+ e.g. by the built-in tools to load the rcParams at instantiation time).
+ """
+
+ description = None
+ """
+ Description of the Tool.
+
+ `str`: Tooltip used if the Tool is included in a Toolbar.
+ """
+
+ image = None
+ """
+ Icon filename.
+
+ ``str | None``: Filename of the Toolbar icon; either absolute, or relative to the
+ directory containing the Python source file where the ``Tool.image`` class attribute
+ is defined (in the latter case, this cannot be defined as an instance attribute).
+ In either case, the extension is optional; leaving it off lets individual backends
+ select the icon format they prefer. If None, the *name* is used as a label in the
+ toolbar button.
+ """
+
+ def __init__(self, toolmanager, name):
+ self._name = name
+ self._toolmanager = toolmanager
+ self._figure = None
+
+ name = property(
+ lambda self: self._name,
+ doc="The tool id (str, must be unique among tools of a tool manager).")
+ toolmanager = property(
+ lambda self: self._toolmanager,
+ doc="The `.ToolManager` that controls this tool.")
+ canvas = property(
+ lambda self: self._figure.canvas if self._figure is not None else None,
+ doc="The canvas of the figure affected by this tool, or None.")
+
+ def set_figure(self, figure):
+ self._figure = figure
+
+ figure = property(
+ lambda self: self._figure,
+ # The setter must explicitly call self.set_figure so that subclasses can
+ # meaningfully override it.
+ lambda self, figure: self.set_figure(figure),
+ doc="The Figure affected by this tool, or None.")
+
+ def _make_classic_style_pseudo_toolbar(self):
+ """
+ Return a placeholder object with a single `canvas` attribute.
+
+ This is useful to reuse the implementations of tools already provided
+ by the classic Toolbars.
+ """
+ return SimpleNamespace(canvas=self.canvas)
+
+ def trigger(self, sender, event, data=None):
+ """
+ Called when this tool gets used.
+
+ This method is called by `.ToolManager.trigger_tool`.
+
+ Parameters
+ ----------
+ event : `.Event`
+ The canvas event that caused this tool to be called.
+ sender : object
+ Object that requested the tool to be triggered.
+ data : object
+ Extra data.
+ """
+ pass
+
+
+class ToolToggleBase(ToolBase):
+ """
+ Toggleable tool.
+
+ Every time it is triggered, it switches between enable and disable.
+
+ Parameters
+ ----------
+ ``*args``
+ Variable length argument to be used by the Tool.
+ ``**kwargs``
+ `toggled` if present and True, sets the initial state of the Tool
+ Arbitrary keyword arguments to be consumed by the Tool
+ """
+
+ radio_group = None
+ """
+ Attribute to group 'radio' like tools (mutually exclusive).
+
+ `str` that identifies the group or **None** if not belonging to a group.
+ """
+
+ cursor = None
+ """Cursor to use when the tool is active."""
+
+ default_toggled = False
+ """Default of toggled state."""
+
+ def __init__(self, *args, **kwargs):
+ self._toggled = kwargs.pop('toggled', self.default_toggled)
+ super().__init__(*args, **kwargs)
+
+ def trigger(self, sender, event, data=None):
+ """Calls `enable` or `disable` based on `toggled` value."""
+ if self._toggled:
+ self.disable(event)
+ else:
+ self.enable(event)
+ self._toggled = not self._toggled
+
+ def enable(self, event=None):
+ """
+ Enable the toggle tool.
+
+ `trigger` calls this method when `toggled` is False.
+ """
+ pass
+
+ def disable(self, event=None):
+ """
+ Disable the toggle tool.
+
+ `trigger` call this method when `toggled` is True.
+
+ This can happen in different circumstances.
+
+ * Click on the toolbar tool button.
+ * Call to `matplotlib.backend_managers.ToolManager.trigger_tool`.
+ * Another `ToolToggleBase` derived tool is triggered
+ (from the same `.ToolManager`).
+ """
+ pass
+
+ @property
+ def toggled(self):
+ """State of the toggled tool."""
+ return self._toggled
+
+ def set_figure(self, figure):
+ toggled = self.toggled
+ if toggled:
+ if self.figure:
+ self.trigger(self, None)
+ else:
+ # if no figure the internal state is not changed
+ # we change it here so next call to trigger will change it back
+ self._toggled = False
+ super().set_figure(figure)
+ if toggled:
+ if figure:
+ self.trigger(self, None)
+ else:
+ # if there is no figure, trigger won't change the internal
+ # state we change it back
+ self._toggled = True
+
+
+class ToolSetCursor(ToolBase):
+ """
+ Change to the current cursor while inaxes.
+
+ This tool, keeps track of all `ToolToggleBase` derived tools, and updates
+ the cursor when a tool gets triggered.
+ """
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self._id_drag = None
+ self._current_tool = None
+ self._default_cursor = cursors.POINTER
+ self._last_cursor = self._default_cursor
+ self.toolmanager.toolmanager_connect('tool_added_event',
+ self._add_tool_cbk)
+ for tool in self.toolmanager.tools.values(): # process current tools
+ self._add_tool_cbk(mpl.backend_managers.ToolEvent(
+ 'tool_added_event', self.toolmanager, tool))
+
+ def set_figure(self, figure):
+ if self._id_drag:
+ self.canvas.mpl_disconnect(self._id_drag)
+ super().set_figure(figure)
+ if figure:
+ self._id_drag = self.canvas.mpl_connect(
+ 'motion_notify_event', self._set_cursor_cbk)
+
+ def _add_tool_cbk(self, event):
+ """Process every newly added tool."""
+ if getattr(event.tool, 'cursor', None) is not None:
+ self.toolmanager.toolmanager_connect(
+ f'tool_trigger_{event.tool.name}', self._tool_trigger_cbk)
+
+ def _tool_trigger_cbk(self, event):
+ self._current_tool = event.tool if event.tool.toggled else None
+ self._set_cursor_cbk(event.canvasevent)
+
+ def _set_cursor_cbk(self, event):
+ if not event or not self.canvas:
+ return
+ if (self._current_tool and getattr(event, "inaxes", None)
+ and event.inaxes.get_navigate()):
+ if self._last_cursor != self._current_tool.cursor:
+ self.canvas.set_cursor(self._current_tool.cursor)
+ self._last_cursor = self._current_tool.cursor
+ elif self._last_cursor != self._default_cursor:
+ self.canvas.set_cursor(self._default_cursor)
+ self._last_cursor = self._default_cursor
+
+
+class ToolCursorPosition(ToolBase):
+ """
+ Send message with the current pointer position.
+
+ This tool runs in the background reporting the position of the cursor.
+ """
+ def __init__(self, *args, **kwargs):
+ self._id_drag = None
+ super().__init__(*args, **kwargs)
+
+ def set_figure(self, figure):
+ if self._id_drag:
+ self.canvas.mpl_disconnect(self._id_drag)
+ super().set_figure(figure)
+ if figure:
+ self._id_drag = self.canvas.mpl_connect(
+ 'motion_notify_event', self.send_message)
+
+ def send_message(self, event):
+ """Call `matplotlib.backend_managers.ToolManager.message_event`."""
+ if self.toolmanager.messagelock.locked():
+ return
+
+ from matplotlib.backend_bases import NavigationToolbar2
+ message = NavigationToolbar2._mouse_event_to_message(event)
+ self.toolmanager.message_event(message, self)
+
+
+class RubberbandBase(ToolBase):
+ """Draw and remove a rubberband."""
+ def trigger(self, sender, event, data=None):
+ """Call `draw_rubberband` or `remove_rubberband` based on data."""
+ if not self.figure.canvas.widgetlock.available(sender):
+ return
+ if data is not None:
+ self.draw_rubberband(*data)
+ else:
+ self.remove_rubberband()
+
+ def draw_rubberband(self, *data):
+ """
+ Draw rubberband.
+
+ This method must get implemented per backend.
+ """
+ raise NotImplementedError
+
+ def remove_rubberband(self):
+ """
+ Remove rubberband.
+
+ This method should get implemented per backend.
+ """
+ pass
+
+
+class ToolQuit(ToolBase):
+ """Tool to call the figure manager destroy method."""
+
+ description = 'Quit the figure'
+ default_keymap = property(lambda self: mpl.rcParams['keymap.quit'])
+
+ def trigger(self, sender, event, data=None):
+ Gcf.destroy_fig(self.figure)
+
+
+class ToolQuitAll(ToolBase):
+ """Tool to call the figure manager destroy method."""
+
+ description = 'Quit all figures'
+ default_keymap = property(lambda self: mpl.rcParams['keymap.quit_all'])
+
+ def trigger(self, sender, event, data=None):
+ Gcf.destroy_all()
+
+
+class ToolGrid(ToolBase):
+ """Tool to toggle the major grids of the figure."""
+
+ description = 'Toggle major grids'
+ default_keymap = property(lambda self: mpl.rcParams['keymap.grid'])
+
+ def trigger(self, sender, event, data=None):
+ sentinel = str(uuid.uuid4())
+ # Trigger grid switching by temporarily setting :rc:`keymap.grid`
+ # to a unique key and sending an appropriate event.
+ with (cbook._setattr_cm(event, key=sentinel),
+ mpl.rc_context({'keymap.grid': sentinel})):
+ mpl.backend_bases.key_press_handler(event, self.figure.canvas)
+
+
+class ToolMinorGrid(ToolBase):
+ """Tool to toggle the major and minor grids of the figure."""
+
+ description = 'Toggle major and minor grids'
+ default_keymap = property(lambda self: mpl.rcParams['keymap.grid_minor'])
+
+ def trigger(self, sender, event, data=None):
+ sentinel = str(uuid.uuid4())
+ # Trigger grid switching by temporarily setting :rc:`keymap.grid_minor`
+ # to a unique key and sending an appropriate event.
+ with (cbook._setattr_cm(event, key=sentinel),
+ mpl.rc_context({'keymap.grid_minor': sentinel})):
+ mpl.backend_bases.key_press_handler(event, self.figure.canvas)
+
+
+class ToolFullScreen(ToolBase):
+ """Tool to toggle full screen."""
+
+ description = 'Toggle fullscreen mode'
+ default_keymap = property(lambda self: mpl.rcParams['keymap.fullscreen'])
+
+ def trigger(self, sender, event, data=None):
+ self.figure.canvas.manager.full_screen_toggle()
+
+
+class AxisScaleBase(ToolToggleBase):
+ """Base Tool to toggle between linear and logarithmic."""
+
+ def trigger(self, sender, event, data=None):
+ if event.inaxes is None:
+ return
+ super().trigger(sender, event, data)
+
+ def enable(self, event=None):
+ self.set_scale(event.inaxes, 'log')
+ self.figure.canvas.draw_idle()
+
+ def disable(self, event=None):
+ self.set_scale(event.inaxes, 'linear')
+ self.figure.canvas.draw_idle()
+
+
+class ToolYScale(AxisScaleBase):
+ """Tool to toggle between linear and logarithmic scales on the Y axis."""
+
+ description = 'Toggle scale Y axis'
+ default_keymap = property(lambda self: mpl.rcParams['keymap.yscale'])
+
+ def set_scale(self, ax, scale):
+ ax.set_yscale(scale)
+
+
+class ToolXScale(AxisScaleBase):
+ """Tool to toggle between linear and logarithmic scales on the X axis."""
+
+ description = 'Toggle scale X axis'
+ default_keymap = property(lambda self: mpl.rcParams['keymap.xscale'])
+
+ def set_scale(self, ax, scale):
+ ax.set_xscale(scale)
+
+
+class ToolViewsPositions(ToolBase):
+ """
+ Auxiliary Tool to handle changes in views and positions.
+
+ Runs in the background and should get used by all the tools that
+ need to access the figure's history of views and positions, e.g.
+
+ * `ToolZoom`
+ * `ToolPan`
+ * `ToolHome`
+ * `ToolBack`
+ * `ToolForward`
+ """
+
+ def __init__(self, *args, **kwargs):
+ self.views = WeakKeyDictionary()
+ self.positions = WeakKeyDictionary()
+ self.home_views = WeakKeyDictionary()
+ super().__init__(*args, **kwargs)
+
+ def add_figure(self, figure):
+ """Add the current figure to the stack of views and positions."""
+
+ if figure not in self.views:
+ self.views[figure] = cbook._Stack()
+ self.positions[figure] = cbook._Stack()
+ self.home_views[figure] = WeakKeyDictionary()
+ # Define Home
+ self.push_current(figure)
+ # Make sure we add a home view for new Axes as they're added
+ figure.add_axobserver(lambda fig: self.update_home_views(fig))
+
+ def clear(self, figure):
+ """Reset the Axes stack."""
+ if figure in self.views:
+ self.views[figure].clear()
+ self.positions[figure].clear()
+ self.home_views[figure].clear()
+ self.update_home_views()
+
+ def update_view(self):
+ """
+ Update the view limits and position for each Axes from the current
+ stack position. If any Axes are present in the figure that aren't in
+ the current stack position, use the home view limits for those Axes and
+ don't update *any* positions.
+ """
+
+ views = self.views[self.figure]()
+ if views is None:
+ return
+ pos = self.positions[self.figure]()
+ if pos is None:
+ return
+ home_views = self.home_views[self.figure]
+ all_axes = self.figure.get_axes()
+ for a in all_axes:
+ if a in views:
+ cur_view = views[a]
+ else:
+ cur_view = home_views[a]
+ a._set_view(cur_view)
+
+ if set(all_axes).issubset(pos):
+ for a in all_axes:
+ # Restore both the original and modified positions
+ a._set_position(pos[a][0], 'original')
+ a._set_position(pos[a][1], 'active')
+
+ self.figure.canvas.draw_idle()
+
+ def push_current(self, figure=None):
+ """
+ Push the current view limits and position onto their respective stacks.
+ """
+ if not figure:
+ figure = self.figure
+ views = WeakKeyDictionary()
+ pos = WeakKeyDictionary()
+ for a in figure.get_axes():
+ views[a] = a._get_view()
+ pos[a] = self._axes_pos(a)
+ self.views[figure].push(views)
+ self.positions[figure].push(pos)
+
+ def _axes_pos(self, ax):
+ """
+ Return the original and modified positions for the specified Axes.
+
+ Parameters
+ ----------
+ ax : matplotlib.axes.Axes
+ The `.Axes` to get the positions for.
+
+ Returns
+ -------
+ original_position, modified_position
+ A tuple of the original and modified positions.
+ """
+
+ return (ax.get_position(True).frozen(),
+ ax.get_position().frozen())
+
+ def update_home_views(self, figure=None):
+ """
+ Make sure that ``self.home_views`` has an entry for all Axes present
+ in the figure.
+ """
+
+ if not figure:
+ figure = self.figure
+ for a in figure.get_axes():
+ if a not in self.home_views[figure]:
+ self.home_views[figure][a] = a._get_view()
+
+ def home(self):
+ """Recall the first view and position from the stack."""
+ self.views[self.figure].home()
+ self.positions[self.figure].home()
+
+ def back(self):
+ """Back one step in the stack of views and positions."""
+ self.views[self.figure].back()
+ self.positions[self.figure].back()
+
+ def forward(self):
+ """Forward one step in the stack of views and positions."""
+ self.views[self.figure].forward()
+ self.positions[self.figure].forward()
+
+
+class ViewsPositionsBase(ToolBase):
+ """Base class for `ToolHome`, `ToolBack` and `ToolForward`."""
+
+ _on_trigger = None
+
+ def trigger(self, sender, event, data=None):
+ self.toolmanager.get_tool(_views_positions).add_figure(self.figure)
+ getattr(self.toolmanager.get_tool(_views_positions),
+ self._on_trigger)()
+ self.toolmanager.get_tool(_views_positions).update_view()
+
+
+class ToolHome(ViewsPositionsBase):
+ """Restore the original view limits."""
+
+ description = 'Reset original view'
+ image = 'mpl-data/images/home'
+ default_keymap = property(lambda self: mpl.rcParams['keymap.home'])
+ _on_trigger = 'home'
+
+
+class ToolBack(ViewsPositionsBase):
+ """Move back up the view limits stack."""
+
+ description = 'Back to previous view'
+ image = 'mpl-data/images/back'
+ default_keymap = property(lambda self: mpl.rcParams['keymap.back'])
+ _on_trigger = 'back'
+
+
+class ToolForward(ViewsPositionsBase):
+ """Move forward in the view lim stack."""
+
+ description = 'Forward to next view'
+ image = 'mpl-data/images/forward'
+ default_keymap = property(lambda self: mpl.rcParams['keymap.forward'])
+ _on_trigger = 'forward'
+
+
+class ConfigureSubplotsBase(ToolBase):
+ """Base tool for the configuration of subplots."""
+
+ description = 'Configure subplots'
+ image = 'mpl-data/images/subplots'
+
+
+class SaveFigureBase(ToolBase):
+ """Base tool for figure saving."""
+
+ description = 'Save the figure'
+ image = 'mpl-data/images/filesave'
+ default_keymap = property(lambda self: mpl.rcParams['keymap.save'])
+
+
+class ZoomPanBase(ToolToggleBase):
+ """Base class for `ToolZoom` and `ToolPan`."""
+ def __init__(self, *args):
+ super().__init__(*args)
+ self._button_pressed = None
+ self._xypress = None
+ self._idPress = None
+ self._idRelease = None
+ self._idScroll = None
+ self.base_scale = 2.
+ self.scrollthresh = .5 # .5 second scroll threshold
+ self.lastscroll = time.time()-self.scrollthresh
+
+ def enable(self, event=None):
+ """Connect press/release events and lock the canvas."""
+ self.figure.canvas.widgetlock(self)
+ self._idPress = self.figure.canvas.mpl_connect(
+ 'button_press_event', self._press)
+ self._idRelease = self.figure.canvas.mpl_connect(
+ 'button_release_event', self._release)
+ self._idScroll = self.figure.canvas.mpl_connect(
+ 'scroll_event', self.scroll_zoom)
+
+ def disable(self, event=None):
+ """Release the canvas and disconnect press/release events."""
+ self._cancel_action()
+ self.figure.canvas.widgetlock.release(self)
+ self.figure.canvas.mpl_disconnect(self._idPress)
+ self.figure.canvas.mpl_disconnect(self._idRelease)
+ self.figure.canvas.mpl_disconnect(self._idScroll)
+
+ def trigger(self, sender, event, data=None):
+ self.toolmanager.get_tool(_views_positions).add_figure(self.figure)
+ super().trigger(sender, event, data)
+ new_navigate_mode = self.name.upper() if self.toggled else None
+ for ax in self.figure.axes:
+ ax.set_navigate_mode(new_navigate_mode)
+
+ def scroll_zoom(self, event):
+ # https://gist.github.com/tacaswell/3144287
+ if event.inaxes is None:
+ return
+
+ if event.button == 'up':
+ # deal with zoom in
+ scl = self.base_scale
+ elif event.button == 'down':
+ # deal with zoom out
+ scl = 1/self.base_scale
+ else:
+ # deal with something that should never happen
+ scl = 1
+
+ ax = event.inaxes
+ ax._set_view_from_bbox([event.x, event.y, scl])
+
+ # If last scroll was done within the timing threshold, delete the
+ # previous view
+ if (time.time()-self.lastscroll) < self.scrollthresh:
+ self.toolmanager.get_tool(_views_positions).back()
+
+ self.figure.canvas.draw_idle() # force re-draw
+
+ self.lastscroll = time.time()
+ self.toolmanager.get_tool(_views_positions).push_current()
+
+
+class ToolZoom(ZoomPanBase):
+ """A Tool for zooming using a rectangle selector."""
+
+ description = 'Zoom to rectangle'
+ image = 'mpl-data/images/zoom_to_rect'
+ default_keymap = property(lambda self: mpl.rcParams['keymap.zoom'])
+ cursor = cursors.SELECT_REGION
+ radio_group = 'default'
+
+ def __init__(self, *args):
+ super().__init__(*args)
+ self._ids_zoom = []
+
+ def _cancel_action(self):
+ for zoom_id in self._ids_zoom:
+ self.figure.canvas.mpl_disconnect(zoom_id)
+ self.toolmanager.trigger_tool('rubberband', self)
+ self.figure.canvas.draw_idle()
+ self._xypress = None
+ self._button_pressed = None
+ self._ids_zoom = []
+ return
+
+ def _press(self, event):
+ """Callback for mouse button presses in zoom-to-rectangle mode."""
+
+ # If we're already in the middle of a zoom, pressing another
+ # button works to "cancel"
+ if self._ids_zoom:
+ self._cancel_action()
+
+ if event.button == 1:
+ self._button_pressed = 1
+ elif event.button == 3:
+ self._button_pressed = 3
+ else:
+ self._cancel_action()
+ return
+
+ x, y = event.x, event.y
+
+ self._xypress = []
+ for i, a in enumerate(self.figure.get_axes()):
+ if (x is not None and y is not None and a.in_axes(event) and
+ a.get_navigate() and a.can_zoom()):
+ self._xypress.append((x, y, a, i, a._get_view()))
+
+ id1 = self.figure.canvas.mpl_connect(
+ 'motion_notify_event', self._mouse_move)
+ id2 = self.figure.canvas.mpl_connect(
+ 'key_press_event', self._switch_on_zoom_mode)
+ id3 = self.figure.canvas.mpl_connect(
+ 'key_release_event', self._switch_off_zoom_mode)
+
+ self._ids_zoom = id1, id2, id3
+ self._zoom_mode = event.key
+
+ def _switch_on_zoom_mode(self, event):
+ self._zoom_mode = event.key
+ self._mouse_move(event)
+
+ def _switch_off_zoom_mode(self, event):
+ self._zoom_mode = None
+ self._mouse_move(event)
+
+ def _mouse_move(self, event):
+ """Callback for mouse moves in zoom-to-rectangle mode."""
+
+ if self._xypress:
+ x, y = event.x, event.y
+ lastx, lasty, a, ind, view = self._xypress[0]
+ (x1, y1), (x2, y2) = np.clip(
+ [[lastx, lasty], [x, y]], a.bbox.min, a.bbox.max)
+ if self._zoom_mode == "x":
+ y1, y2 = a.bbox.intervaly
+ elif self._zoom_mode == "y":
+ x1, x2 = a.bbox.intervalx
+ self.toolmanager.trigger_tool(
+ 'rubberband', self, data=(x1, y1, x2, y2))
+
+ def _release(self, event):
+ """Callback for mouse button releases in zoom-to-rectangle mode."""
+
+ for zoom_id in self._ids_zoom:
+ self.figure.canvas.mpl_disconnect(zoom_id)
+ self._ids_zoom = []
+
+ if not self._xypress:
+ self._cancel_action()
+ return
+
+ done_ax = []
+
+ for cur_xypress in self._xypress:
+ x, y = event.x, event.y
+ lastx, lasty, a, _ind, view = cur_xypress
+ # ignore singular clicks - 5 pixels is a threshold
+ if abs(x - lastx) < 5 or abs(y - lasty) < 5:
+ self._cancel_action()
+ return
+
+ # detect twinx, twiny Axes and avoid double zooming
+ twinx = any(a.get_shared_x_axes().joined(a, a1) for a1 in done_ax)
+ twiny = any(a.get_shared_y_axes().joined(a, a1) for a1 in done_ax)
+ done_ax.append(a)
+
+ if self._button_pressed == 1:
+ direction = 'in'
+ elif self._button_pressed == 3:
+ direction = 'out'
+ else:
+ continue
+
+ a._set_view_from_bbox((lastx, lasty, x, y), direction,
+ self._zoom_mode, twinx, twiny)
+
+ self._zoom_mode = None
+ self.toolmanager.get_tool(_views_positions).push_current()
+ self._cancel_action()
+
+
+class ToolPan(ZoomPanBase):
+ """Pan Axes with left mouse, zoom with right."""
+
+ default_keymap = property(lambda self: mpl.rcParams['keymap.pan'])
+ description = 'Pan axes with left mouse, zoom with right'
+ image = 'mpl-data/images/move'
+ cursor = cursors.MOVE
+ radio_group = 'default'
+
+ def __init__(self, *args):
+ super().__init__(*args)
+ self._id_drag = None
+
+ def _cancel_action(self):
+ self._button_pressed = None
+ self._xypress = []
+ self.figure.canvas.mpl_disconnect(self._id_drag)
+ self.toolmanager.messagelock.release(self)
+ self.figure.canvas.draw_idle()
+
+ def _press(self, event):
+ if event.button == 1:
+ self._button_pressed = 1
+ elif event.button == 3:
+ self._button_pressed = 3
+ else:
+ self._cancel_action()
+ return
+
+ x, y = event.x, event.y
+
+ self._xypress = []
+ for i, a in enumerate(self.figure.get_axes()):
+ if (x is not None and y is not None and a.in_axes(event) and
+ a.get_navigate() and a.can_pan()):
+ a.start_pan(x, y, event.button)
+ self._xypress.append((a, i))
+ self.toolmanager.messagelock(self)
+ self._id_drag = self.figure.canvas.mpl_connect(
+ 'motion_notify_event', self._mouse_move)
+
+ def _release(self, event):
+ if self._button_pressed is None:
+ self._cancel_action()
+ return
+
+ self.figure.canvas.mpl_disconnect(self._id_drag)
+ self.toolmanager.messagelock.release(self)
+
+ for a, _ind in self._xypress:
+ a.end_pan()
+ if not self._xypress:
+ self._cancel_action()
+ return
+
+ self.toolmanager.get_tool(_views_positions).push_current()
+ self._cancel_action()
+
+ def _mouse_move(self, event):
+ for a, _ind in self._xypress:
+ # safer to use the recorded button at the _press than current
+ # button: # multiple button can get pressed during motion...
+ a.drag_pan(self._button_pressed, event.key, event.x, event.y)
+ self.toolmanager.canvas.draw_idle()
+
+
+class ToolHelpBase(ToolBase):
+ description = 'Print tool list, shortcuts and description'
+ default_keymap = property(lambda self: mpl.rcParams['keymap.help'])
+ image = 'mpl-data/images/help'
+
+ @staticmethod
+ def format_shortcut(key_sequence):
+ """
+ Convert a shortcut string from the notation used in rc config to the
+ standard notation for displaying shortcuts, e.g. 'ctrl+a' -> 'Ctrl+A'.
+ """
+ return (key_sequence if len(key_sequence) == 1 else
+ re.sub(r"\+[A-Z]", r"+Shift\g<0>", key_sequence).title())
+
+ def _format_tool_keymap(self, name):
+ keymaps = self.toolmanager.get_tool_keymap(name)
+ return ", ".join(self.format_shortcut(keymap) for keymap in keymaps)
+
+ def _get_help_entries(self):
+ return [(name, self._format_tool_keymap(name), tool.description)
+ for name, tool in sorted(self.toolmanager.tools.items())
+ if tool.description]
+
+ def _get_help_text(self):
+ entries = self._get_help_entries()
+ entries = ["{}: {}\n\t{}".format(*entry) for entry in entries]
+ return "\n".join(entries)
+
+ def _get_help_html(self):
+ fmt = "{} {} {} "
+ rows = [fmt.format(
+ "Action ", "Shortcuts ", "Description ")]
+ rows += [fmt.format(*row) for row in self._get_help_entries()]
+ return (""
+ "" + rows[0] + " "
+ "".join(rows[1:]) + "
")
+
+
+class ToolCopyToClipboardBase(ToolBase):
+ """Tool to copy the figure to the clipboard."""
+
+ description = 'Copy the canvas figure to clipboard'
+ default_keymap = property(lambda self: mpl.rcParams['keymap.copy'])
+
+ def trigger(self, *args, **kwargs):
+ message = "Copy tool is not available"
+ self.toolmanager.message_event(message, self)
+
+
+default_tools = {'home': ToolHome, 'back': ToolBack, 'forward': ToolForward,
+ 'zoom': ToolZoom, 'pan': ToolPan,
+ 'subplots': ConfigureSubplotsBase,
+ 'save': SaveFigureBase,
+ 'grid': ToolGrid,
+ 'grid_minor': ToolMinorGrid,
+ 'fullscreen': ToolFullScreen,
+ 'quit': ToolQuit,
+ 'quit_all': ToolQuitAll,
+ 'xscale': ToolXScale,
+ 'yscale': ToolYScale,
+ 'position': ToolCursorPosition,
+ _views_positions: ToolViewsPositions,
+ 'cursor': ToolSetCursor,
+ 'rubberband': RubberbandBase,
+ 'help': ToolHelpBase,
+ 'copy': ToolCopyToClipboardBase,
+ }
+
+default_toolbar_tools = [['navigation', ['home', 'back', 'forward']],
+ ['zoompan', ['pan', 'zoom', 'subplots']],
+ ['io', ['save', 'help']]]
+
+
+def add_tools_to_manager(toolmanager, tools=default_tools):
+ """
+ Add multiple tools to a `.ToolManager`.
+
+ Parameters
+ ----------
+ toolmanager : `.backend_managers.ToolManager`
+ Manager to which the tools are added.
+ tools : {str: class_like}, optional
+ The tools to add in a {name: tool} dict, see
+ `.backend_managers.ToolManager.add_tool` for more info.
+ """
+
+ for name, tool in tools.items():
+ toolmanager.add_tool(name, tool)
+
+
+def add_tools_to_container(container, tools=default_toolbar_tools):
+ """
+ Add multiple tools to the container.
+
+ Parameters
+ ----------
+ container : Container
+ `.backend_bases.ToolContainerBase` object that will get the tools
+ added.
+ tools : list, optional
+ List in the form ``[[group1, [tool1, tool2 ...]], [group2, [...]]]``
+ where the tools ``[tool1, tool2, ...]`` will display in group1.
+ See `.backend_bases.ToolContainerBase.add_tool` for details.
+ """
+
+ for group, grouptools in tools:
+ for position, tool in enumerate(grouptools):
+ container.add_tool(tool, group, position)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/backend_tools.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/backend_tools.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..32fe8c2f5a7982ce5e2b07a58ac142c645a9ce2b
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/backend_tools.pyi
@@ -0,0 +1,121 @@
+import enum
+from matplotlib import cbook
+from matplotlib.axes import Axes
+from matplotlib.backend_bases import ToolContainerBase, FigureCanvasBase
+from matplotlib.backend_managers import ToolManager, ToolEvent
+from matplotlib.figure import Figure
+from matplotlib.scale import ScaleBase
+
+from typing import Any, cast
+
+class Cursors(enum.IntEnum):
+ POINTER = cast(int, ...)
+ HAND = cast(int, ...)
+ SELECT_REGION = cast(int, ...)
+ MOVE = cast(int, ...)
+ WAIT = cast(int, ...)
+ RESIZE_HORIZONTAL = cast(int, ...)
+ RESIZE_VERTICAL = cast(int, ...)
+
+cursors = Cursors
+
+class ToolBase:
+ @property
+ def default_keymap(self) -> list[str] | None: ...
+ description: str | None
+ image: str | None
+ def __init__(self, toolmanager: ToolManager, name: str) -> None: ...
+ @property
+ def name(self) -> str: ...
+ @property
+ def toolmanager(self) -> ToolManager: ...
+ @property
+ def canvas(self) -> FigureCanvasBase | None: ...
+ @property
+ def figure(self) -> Figure | None: ...
+ @figure.setter
+ def figure(self, figure: Figure | None) -> None: ...
+ def set_figure(self, figure: Figure | None) -> None: ...
+ def trigger(self, sender: Any, event: ToolEvent, data: Any = ...) -> None: ...
+
+class ToolToggleBase(ToolBase):
+ radio_group: str | None
+ cursor: Cursors | None
+ default_toggled: bool
+ def __init__(self, *args, **kwargs) -> None: ...
+ def enable(self, event: ToolEvent | None = ...) -> None: ...
+ def disable(self, event: ToolEvent | None = ...) -> None: ...
+ @property
+ def toggled(self) -> bool: ...
+ def set_figure(self, figure: Figure | None) -> None: ...
+
+class ToolSetCursor(ToolBase): ...
+
+class ToolCursorPosition(ToolBase):
+ def send_message(self, event: ToolEvent) -> None: ...
+
+class RubberbandBase(ToolBase):
+ def draw_rubberband(self, *data) -> None: ...
+ def remove_rubberband(self) -> None: ...
+
+class ToolQuit(ToolBase): ...
+class ToolQuitAll(ToolBase): ...
+class ToolGrid(ToolBase): ...
+class ToolMinorGrid(ToolBase): ...
+class ToolFullScreen(ToolBase): ...
+
+class AxisScaleBase(ToolToggleBase):
+ def enable(self, event: ToolEvent | None = ...) -> None: ...
+ def disable(self, event: ToolEvent | None = ...) -> None: ...
+
+class ToolYScale(AxisScaleBase):
+ def set_scale(self, ax: Axes, scale: str | ScaleBase) -> None: ...
+
+class ToolXScale(AxisScaleBase):
+ def set_scale(self, ax, scale: str | ScaleBase) -> None: ...
+
+class ToolViewsPositions(ToolBase):
+ views: dict[Figure | Axes, cbook._Stack]
+ positions: dict[Figure | Axes, cbook._Stack]
+ home_views: dict[Figure, dict[Axes, tuple[float, float, float, float]]]
+ def add_figure(self, figure: Figure) -> None: ...
+ def clear(self, figure: Figure) -> None: ...
+ def update_view(self) -> None: ...
+ def push_current(self, figure: Figure | None = ...) -> None: ...
+ def update_home_views(self, figure: Figure | None = ...) -> None: ...
+ def home(self) -> None: ...
+ def back(self) -> None: ...
+ def forward(self) -> None: ...
+
+class ViewsPositionsBase(ToolBase): ...
+class ToolHome(ViewsPositionsBase): ...
+class ToolBack(ViewsPositionsBase): ...
+class ToolForward(ViewsPositionsBase): ...
+class ConfigureSubplotsBase(ToolBase): ...
+class SaveFigureBase(ToolBase): ...
+
+class ZoomPanBase(ToolToggleBase):
+ base_scale: float
+ scrollthresh: float
+ lastscroll: float
+ def __init__(self, *args) -> None: ...
+ def enable(self, event: ToolEvent | None = ...) -> None: ...
+ def disable(self, event: ToolEvent | None = ...) -> None: ...
+ def scroll_zoom(self, event: ToolEvent) -> None: ...
+
+class ToolZoom(ZoomPanBase): ...
+class ToolPan(ZoomPanBase): ...
+
+class ToolHelpBase(ToolBase):
+ @staticmethod
+ def format_shortcut(key_sequence: str) -> str: ...
+
+class ToolCopyToClipboardBase(ToolBase): ...
+
+default_tools: dict[str, ToolBase]
+default_toolbar_tools: list[list[str | list[str]]]
+
+def add_tools_to_manager(
+ toolmanager: ToolManager, tools: dict[str, type[ToolBase]] = ...
+) -> None: ...
+def add_tools_to_container(container: ToolContainerBase, tools: list[Any] = ...) -> None: ...
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/bezier.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/bezier.py
new file mode 100644
index 0000000000000000000000000000000000000000..42a6b478d729f3b2837e11e6767b84ac5972654d
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/bezier.py
@@ -0,0 +1,602 @@
+"""
+A module providing some utility functions regarding BƩzier path manipulation.
+"""
+
+from functools import lru_cache
+import math
+import warnings
+
+import numpy as np
+
+from matplotlib import _api
+
+
+# same algorithm as 3.8's math.comb
+@np.vectorize
+@lru_cache(maxsize=128)
+def _comb(n, k):
+ if k > n:
+ return 0
+ k = min(k, n - k)
+ i = np.arange(1, k + 1)
+ return np.prod((n + 1 - i)/i).astype(int)
+
+
+class NonIntersectingPathException(ValueError):
+ pass
+
+
+# some functions
+
+
+def get_intersection(cx1, cy1, cos_t1, sin_t1,
+ cx2, cy2, cos_t2, sin_t2):
+ """
+ Return the intersection between the line through (*cx1*, *cy1*) at angle
+ *t1* and the line through (*cx2*, *cy2*) at angle *t2*.
+ """
+
+ # line1 => sin_t1 * (x - cx1) - cos_t1 * (y - cy1) = 0.
+ # line1 => sin_t1 * x + cos_t1 * y = sin_t1*cx1 - cos_t1*cy1
+
+ line1_rhs = sin_t1 * cx1 - cos_t1 * cy1
+ line2_rhs = sin_t2 * cx2 - cos_t2 * cy2
+
+ # rhs matrix
+ a, b = sin_t1, -cos_t1
+ c, d = sin_t2, -cos_t2
+
+ ad_bc = a * d - b * c
+ if abs(ad_bc) < 1e-12:
+ raise ValueError("Given lines do not intersect. Please verify that "
+ "the angles are not equal or differ by 180 degrees.")
+
+ # rhs_inverse
+ a_, b_ = d, -b
+ c_, d_ = -c, a
+ a_, b_, c_, d_ = (k / ad_bc for k in [a_, b_, c_, d_])
+
+ x = a_ * line1_rhs + b_ * line2_rhs
+ y = c_ * line1_rhs + d_ * line2_rhs
+
+ return x, y
+
+
+def get_normal_points(cx, cy, cos_t, sin_t, length):
+ """
+ For a line passing through (*cx*, *cy*) and having an angle *t*, return
+ locations of the two points located along its perpendicular line at the
+ distance of *length*.
+ """
+
+ if length == 0.:
+ return cx, cy, cx, cy
+
+ cos_t1, sin_t1 = sin_t, -cos_t
+ cos_t2, sin_t2 = -sin_t, cos_t
+
+ x1, y1 = length * cos_t1 + cx, length * sin_t1 + cy
+ x2, y2 = length * cos_t2 + cx, length * sin_t2 + cy
+
+ return x1, y1, x2, y2
+
+
+# BEZIER routines
+
+# subdividing bezier curve
+# http://www.cs.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/Bezier/bezier-sub.html
+
+
+def _de_casteljau1(beta, t):
+ next_beta = beta[:-1] * (1 - t) + beta[1:] * t
+ return next_beta
+
+
+def split_de_casteljau(beta, t):
+ """
+ Split a BƩzier segment defined by its control points *beta* into two
+ separate segments divided at *t* and return their control points.
+ """
+ beta = np.asarray(beta)
+ beta_list = [beta]
+ while True:
+ beta = _de_casteljau1(beta, t)
+ beta_list.append(beta)
+ if len(beta) == 1:
+ break
+ left_beta = [beta[0] for beta in beta_list]
+ right_beta = [beta[-1] for beta in reversed(beta_list)]
+
+ return left_beta, right_beta
+
+
+def find_bezier_t_intersecting_with_closedpath(
+ bezier_point_at_t, inside_closedpath, t0=0., t1=1., tolerance=0.01):
+ """
+ Find the intersection of the BƩzier curve with a closed path.
+
+ The intersection point *t* is approximated by two parameters *t0*, *t1*
+ such that *t0* <= *t* <= *t1*.
+
+ Search starts from *t0* and *t1* and uses a simple bisecting algorithm
+ therefore one of the end points must be inside the path while the other
+ doesn't. The search stops when the distance of the points parametrized by
+ *t0* and *t1* gets smaller than the given *tolerance*.
+
+ Parameters
+ ----------
+ bezier_point_at_t : callable
+ A function returning x, y coordinates of the BƩzier at parameter *t*.
+ It must have the signature::
+
+ bezier_point_at_t(t: float) -> tuple[float, float]
+
+ inside_closedpath : callable
+ A function returning True if a given point (x, y) is inside the
+ closed path. It must have the signature::
+
+ inside_closedpath(point: tuple[float, float]) -> bool
+
+ t0, t1 : float
+ Start parameters for the search.
+
+ tolerance : float
+ Maximal allowed distance between the final points.
+
+ Returns
+ -------
+ t0, t1 : float
+ The BƩzier path parameters.
+ """
+ start = bezier_point_at_t(t0)
+ end = bezier_point_at_t(t1)
+
+ start_inside = inside_closedpath(start)
+ end_inside = inside_closedpath(end)
+
+ if start_inside == end_inside and start != end:
+ raise NonIntersectingPathException(
+ "Both points are on the same side of the closed path")
+
+ while True:
+
+ # return if the distance is smaller than the tolerance
+ if np.hypot(start[0] - end[0], start[1] - end[1]) < tolerance:
+ return t0, t1
+
+ # calculate the middle point
+ middle_t = 0.5 * (t0 + t1)
+ middle = bezier_point_at_t(middle_t)
+ middle_inside = inside_closedpath(middle)
+
+ if start_inside ^ middle_inside:
+ t1 = middle_t
+ if end == middle:
+ # Edge case where infinite loop is possible
+ # Caused by large numbers relative to tolerance
+ return t0, t1
+ end = middle
+ else:
+ t0 = middle_t
+ if start == middle:
+ # Edge case where infinite loop is possible
+ # Caused by large numbers relative to tolerance
+ return t0, t1
+ start = middle
+ start_inside = middle_inside
+
+
+class BezierSegment:
+ """
+ A d-dimensional BƩzier segment.
+
+ Parameters
+ ----------
+ control_points : (N, d) array
+ Location of the *N* control points.
+ """
+
+ def __init__(self, control_points):
+ self._cpoints = np.asarray(control_points)
+ self._N, self._d = self._cpoints.shape
+ self._orders = np.arange(self._N)
+ coeff = [math.factorial(self._N - 1)
+ // (math.factorial(i) * math.factorial(self._N - 1 - i))
+ for i in range(self._N)]
+ self._px = (self._cpoints.T * coeff).T
+
+ def __call__(self, t):
+ """
+ Evaluate the BƩzier curve at point(s) *t* in [0, 1].
+
+ Parameters
+ ----------
+ t : (k,) array-like
+ Points at which to evaluate the curve.
+
+ Returns
+ -------
+ (k, d) array
+ Value of the curve for each point in *t*.
+ """
+ t = np.asarray(t)
+ return (np.power.outer(1 - t, self._orders[::-1])
+ * np.power.outer(t, self._orders)) @ self._px
+
+ def point_at_t(self, t):
+ """
+ Evaluate the curve at a single point, returning a tuple of *d* floats.
+ """
+ return tuple(self(t))
+
+ @property
+ def control_points(self):
+ """The control points of the curve."""
+ return self._cpoints
+
+ @property
+ def dimension(self):
+ """The dimension of the curve."""
+ return self._d
+
+ @property
+ def degree(self):
+ """Degree of the polynomial. One less the number of control points."""
+ return self._N - 1
+
+ @property
+ def polynomial_coefficients(self):
+ r"""
+ The polynomial coefficients of the BƩzier curve.
+
+ .. warning:: Follows opposite convention from `numpy.polyval`.
+
+ Returns
+ -------
+ (n+1, d) array
+ Coefficients after expanding in polynomial basis, where :math:`n`
+ is the degree of the BƩzier curve and :math:`d` its dimension.
+ These are the numbers (:math:`C_j`) such that the curve can be
+ written :math:`\sum_{j=0}^n C_j t^j`.
+
+ Notes
+ -----
+ The coefficients are calculated as
+
+ .. math::
+
+ {n \choose j} \sum_{i=0}^j (-1)^{i+j} {j \choose i} P_i
+
+ where :math:`P_i` are the control points of the curve.
+ """
+ n = self.degree
+ # matplotlib uses n <= 4. overflow plausible starting around n = 15.
+ if n > 10:
+ warnings.warn("Polynomial coefficients formula unstable for high "
+ "order Bezier curves!", RuntimeWarning)
+ P = self.control_points
+ j = np.arange(n+1)[:, None]
+ i = np.arange(n+1)[None, :] # _comb is non-zero for i <= j
+ prefactor = (-1)**(i + j) * _comb(j, i) # j on axis 0, i on axis 1
+ return _comb(n, j) * prefactor @ P # j on axis 0, self.dimension on 1
+
+ def axis_aligned_extrema(self):
+ """
+ Return the dimension and location of the curve's interior extrema.
+
+ The extrema are the points along the curve where one of its partial
+ derivatives is zero.
+
+ Returns
+ -------
+ dims : array of int
+ Index :math:`i` of the partial derivative which is zero at each
+ interior extrema.
+ dzeros : array of float
+ Of same size as dims. The :math:`t` such that :math:`d/dx_i B(t) =
+ 0`
+ """
+ n = self.degree
+ if n <= 1:
+ return np.array([]), np.array([])
+ Cj = self.polynomial_coefficients
+ dCj = np.arange(1, n+1)[:, None] * Cj[1:]
+ dims = []
+ roots = []
+ for i, pi in enumerate(dCj.T):
+ r = np.roots(pi[::-1])
+ roots.append(r)
+ dims.append(np.full_like(r, i))
+ roots = np.concatenate(roots)
+ dims = np.concatenate(dims)
+ in_range = np.isreal(roots) & (roots >= 0) & (roots <= 1)
+ return dims[in_range], np.real(roots)[in_range]
+
+
+def split_bezier_intersecting_with_closedpath(
+ bezier, inside_closedpath, tolerance=0.01):
+ """
+ Split a BƩzier curve into two at the intersection with a closed path.
+
+ Parameters
+ ----------
+ bezier : (N, 2) array-like
+ Control points of the BƩzier segment. See `.BezierSegment`.
+ inside_closedpath : callable
+ A function returning True if a given point (x, y) is inside the
+ closed path. See also `.find_bezier_t_intersecting_with_closedpath`.
+ tolerance : float
+ The tolerance for the intersection. See also
+ `.find_bezier_t_intersecting_with_closedpath`.
+
+ Returns
+ -------
+ left, right
+ Lists of control points for the two BƩzier segments.
+ """
+
+ bz = BezierSegment(bezier)
+ bezier_point_at_t = bz.point_at_t
+
+ t0, t1 = find_bezier_t_intersecting_with_closedpath(
+ bezier_point_at_t, inside_closedpath, tolerance=tolerance)
+
+ _left, _right = split_de_casteljau(bezier, (t0 + t1) / 2.)
+ return _left, _right
+
+
+# matplotlib specific
+
+
+def split_path_inout(path, inside, tolerance=0.01, reorder_inout=False):
+ """
+ Divide a path into two segments at the point where ``inside(x, y)`` becomes
+ False.
+ """
+ from .path import Path
+ path_iter = path.iter_segments()
+
+ ctl_points, command = next(path_iter)
+ begin_inside = inside(ctl_points[-2:]) # true if begin point is inside
+
+ ctl_points_old = ctl_points
+
+ iold = 0
+ i = 1
+
+ for ctl_points, command in path_iter:
+ iold = i
+ i += len(ctl_points) // 2
+ if inside(ctl_points[-2:]) != begin_inside:
+ bezier_path = np.concatenate([ctl_points_old[-2:], ctl_points])
+ break
+ ctl_points_old = ctl_points
+ else:
+ raise ValueError("The path does not intersect with the patch")
+
+ bp = bezier_path.reshape((-1, 2))
+ left, right = split_bezier_intersecting_with_closedpath(
+ bp, inside, tolerance)
+ if len(left) == 2:
+ codes_left = [Path.LINETO]
+ codes_right = [Path.MOVETO, Path.LINETO]
+ elif len(left) == 3:
+ codes_left = [Path.CURVE3, Path.CURVE3]
+ codes_right = [Path.MOVETO, Path.CURVE3, Path.CURVE3]
+ elif len(left) == 4:
+ codes_left = [Path.CURVE4, Path.CURVE4, Path.CURVE4]
+ codes_right = [Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4]
+ else:
+ raise AssertionError("This should never be reached")
+
+ verts_left = left[1:]
+ verts_right = right[:]
+
+ if path.codes is None:
+ path_in = Path(np.concatenate([path.vertices[:i], verts_left]))
+ path_out = Path(np.concatenate([verts_right, path.vertices[i:]]))
+
+ else:
+ path_in = Path(np.concatenate([path.vertices[:iold], verts_left]),
+ np.concatenate([path.codes[:iold], codes_left]))
+
+ path_out = Path(np.concatenate([verts_right, path.vertices[i:]]),
+ np.concatenate([codes_right, path.codes[i:]]))
+
+ if reorder_inout and not begin_inside:
+ path_in, path_out = path_out, path_in
+
+ return path_in, path_out
+
+
+def inside_circle(cx, cy, r):
+ """
+ Return a function that checks whether a point is in a circle with center
+ (*cx*, *cy*) and radius *r*.
+
+ The returned function has the signature::
+
+ f(xy: tuple[float, float]) -> bool
+ """
+ r2 = r ** 2
+
+ def _f(xy):
+ x, y = xy
+ return (x - cx) ** 2 + (y - cy) ** 2 < r2
+ return _f
+
+
+# quadratic Bezier lines
+
+def get_cos_sin(x0, y0, x1, y1):
+ dx, dy = x1 - x0, y1 - y0
+ d = (dx * dx + dy * dy) ** .5
+ # Account for divide by zero
+ if d == 0:
+ return 0.0, 0.0
+ return dx / d, dy / d
+
+
+def check_if_parallel(dx1, dy1, dx2, dy2, tolerance=1.e-5):
+ """
+ Check if two lines are parallel.
+
+ Parameters
+ ----------
+ dx1, dy1, dx2, dy2 : float
+ The gradients *dy*/*dx* of the two lines.
+ tolerance : float
+ The angular tolerance in radians up to which the lines are considered
+ parallel.
+
+ Returns
+ -------
+ is_parallel
+ - 1 if two lines are parallel in same direction.
+ - -1 if two lines are parallel in opposite direction.
+ - False otherwise.
+ """
+ theta1 = np.arctan2(dx1, dy1)
+ theta2 = np.arctan2(dx2, dy2)
+ dtheta = abs(theta1 - theta2)
+ if dtheta < tolerance:
+ return 1
+ elif abs(dtheta - np.pi) < tolerance:
+ return -1
+ else:
+ return False
+
+
+def get_parallels(bezier2, width):
+ """
+ Given the quadratic BƩzier control points *bezier2*, returns
+ control points of quadratic BƩzier lines roughly parallel to given
+ one separated by *width*.
+ """
+
+ # The parallel Bezier lines are constructed by following ways.
+ # c1 and c2 are control points representing the start and end of the
+ # Bezier line.
+ # cm is the middle point
+
+ c1x, c1y = bezier2[0]
+ cmx, cmy = bezier2[1]
+ c2x, c2y = bezier2[2]
+
+ parallel_test = check_if_parallel(c1x - cmx, c1y - cmy,
+ cmx - c2x, cmy - c2y)
+
+ if parallel_test == -1:
+ _api.warn_external(
+ "Lines do not intersect. A straight line is used instead.")
+ cos_t1, sin_t1 = get_cos_sin(c1x, c1y, c2x, c2y)
+ cos_t2, sin_t2 = cos_t1, sin_t1
+ else:
+ # t1 and t2 is the angle between c1 and cm, cm, c2. They are
+ # also an angle of the tangential line of the path at c1 and c2
+ cos_t1, sin_t1 = get_cos_sin(c1x, c1y, cmx, cmy)
+ cos_t2, sin_t2 = get_cos_sin(cmx, cmy, c2x, c2y)
+
+ # find c1_left, c1_right which are located along the lines
+ # through c1 and perpendicular to the tangential lines of the
+ # Bezier path at a distance of width. Same thing for c2_left and
+ # c2_right with respect to c2.
+ c1x_left, c1y_left, c1x_right, c1y_right = (
+ get_normal_points(c1x, c1y, cos_t1, sin_t1, width)
+ )
+ c2x_left, c2y_left, c2x_right, c2y_right = (
+ get_normal_points(c2x, c2y, cos_t2, sin_t2, width)
+ )
+
+ # find cm_left which is the intersecting point of a line through
+ # c1_left with angle t1 and a line through c2_left with angle
+ # t2. Same with cm_right.
+ try:
+ cmx_left, cmy_left = get_intersection(c1x_left, c1y_left, cos_t1,
+ sin_t1, c2x_left, c2y_left,
+ cos_t2, sin_t2)
+ cmx_right, cmy_right = get_intersection(c1x_right, c1y_right, cos_t1,
+ sin_t1, c2x_right, c2y_right,
+ cos_t2, sin_t2)
+ except ValueError:
+ # Special case straight lines, i.e., angle between two lines is
+ # less than the threshold used by get_intersection (we don't use
+ # check_if_parallel as the threshold is not the same).
+ cmx_left, cmy_left = (
+ 0.5 * (c1x_left + c2x_left), 0.5 * (c1y_left + c2y_left)
+ )
+ cmx_right, cmy_right = (
+ 0.5 * (c1x_right + c2x_right), 0.5 * (c1y_right + c2y_right)
+ )
+
+ # the parallel Bezier lines are created with control points of
+ # [c1_left, cm_left, c2_left] and [c1_right, cm_right, c2_right]
+ path_left = [(c1x_left, c1y_left),
+ (cmx_left, cmy_left),
+ (c2x_left, c2y_left)]
+ path_right = [(c1x_right, c1y_right),
+ (cmx_right, cmy_right),
+ (c2x_right, c2y_right)]
+
+ return path_left, path_right
+
+
+def find_control_points(c1x, c1y, mmx, mmy, c2x, c2y):
+ """
+ Find control points of the BƩzier curve passing through (*c1x*, *c1y*),
+ (*mmx*, *mmy*), and (*c2x*, *c2y*), at parametric values 0, 0.5, and 1.
+ """
+ cmx = .5 * (4 * mmx - (c1x + c2x))
+ cmy = .5 * (4 * mmy - (c1y + c2y))
+ return [(c1x, c1y), (cmx, cmy), (c2x, c2y)]
+
+
+def make_wedged_bezier2(bezier2, width, w1=1., wm=0.5, w2=0.):
+ """
+ Being similar to `get_parallels`, returns control points of two quadratic
+ BƩzier lines having a width roughly parallel to given one separated by
+ *width*.
+ """
+
+ # c1, cm, c2
+ c1x, c1y = bezier2[0]
+ cmx, cmy = bezier2[1]
+ c3x, c3y = bezier2[2]
+
+ # t1 and t2 is the angle between c1 and cm, cm, c3.
+ # They are also an angle of the tangential line of the path at c1 and c3
+ cos_t1, sin_t1 = get_cos_sin(c1x, c1y, cmx, cmy)
+ cos_t2, sin_t2 = get_cos_sin(cmx, cmy, c3x, c3y)
+
+ # find c1_left, c1_right which are located along the lines
+ # through c1 and perpendicular to the tangential lines of the
+ # Bezier path at a distance of width. Same thing for c3_left and
+ # c3_right with respect to c3.
+ c1x_left, c1y_left, c1x_right, c1y_right = (
+ get_normal_points(c1x, c1y, cos_t1, sin_t1, width * w1)
+ )
+ c3x_left, c3y_left, c3x_right, c3y_right = (
+ get_normal_points(c3x, c3y, cos_t2, sin_t2, width * w2)
+ )
+
+ # find c12, c23 and c123 which are middle points of c1-cm, cm-c3 and
+ # c12-c23
+ c12x, c12y = (c1x + cmx) * .5, (c1y + cmy) * .5
+ c23x, c23y = (cmx + c3x) * .5, (cmy + c3y) * .5
+ c123x, c123y = (c12x + c23x) * .5, (c12y + c23y) * .5
+
+ # tangential angle of c123 (angle between c12 and c23)
+ cos_t123, sin_t123 = get_cos_sin(c12x, c12y, c23x, c23y)
+
+ c123x_left, c123y_left, c123x_right, c123y_right = (
+ get_normal_points(c123x, c123y, cos_t123, sin_t123, width * wm)
+ )
+
+ path_left = find_control_points(c1x_left, c1y_left,
+ c123x_left, c123y_left,
+ c3x_left, c3y_left)
+ path_right = find_control_points(c1x_right, c1y_right,
+ c123x_right, c123y_right,
+ c3x_right, c3y_right)
+
+ return path_left, path_right
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/bezier.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/bezier.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..ad82b873affd3902290347be2fae3a3b754f35da
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/bezier.pyi
@@ -0,0 +1,74 @@
+from collections.abc import Callable
+from typing import Literal
+
+import numpy as np
+from numpy.typing import ArrayLike
+
+from .path import Path
+
+class NonIntersectingPathException(ValueError): ...
+
+def get_intersection(
+ cx1: float,
+ cy1: float,
+ cos_t1: float,
+ sin_t1: float,
+ cx2: float,
+ cy2: float,
+ cos_t2: float,
+ sin_t2: float,
+) -> tuple[float, float]: ...
+def get_normal_points(
+ cx: float, cy: float, cos_t: float, sin_t: float, length: float
+) -> tuple[float, float, float, float]: ...
+def split_de_casteljau(beta: ArrayLike, t: float) -> tuple[np.ndarray, np.ndarray]: ...
+def find_bezier_t_intersecting_with_closedpath(
+ bezier_point_at_t: Callable[[float], tuple[float, float]],
+ inside_closedpath: Callable[[tuple[float, float]], bool],
+ t0: float = ...,
+ t1: float = ...,
+ tolerance: float = ...,
+) -> tuple[float, float]: ...
+
+# TODO make generic over d, the dimension? ndarraydim
+class BezierSegment:
+ def __init__(self, control_points: ArrayLike) -> None: ...
+ def __call__(self, t: ArrayLike) -> np.ndarray: ...
+ def point_at_t(self, t: float) -> tuple[float, ...]: ...
+ @property
+ def control_points(self) -> np.ndarray: ...
+ @property
+ def dimension(self) -> int: ...
+ @property
+ def degree(self) -> int: ...
+ @property
+ def polynomial_coefficients(self) -> np.ndarray: ...
+ def axis_aligned_extrema(self) -> tuple[np.ndarray, np.ndarray]: ...
+
+def split_bezier_intersecting_with_closedpath(
+ bezier: ArrayLike,
+ inside_closedpath: Callable[[tuple[float, float]], bool],
+ tolerance: float = ...,
+) -> tuple[np.ndarray, np.ndarray]: ...
+def split_path_inout(
+ path: Path,
+ inside: Callable[[tuple[float, float]], bool],
+ tolerance: float = ...,
+ reorder_inout: bool = ...,
+) -> tuple[Path, Path]: ...
+def inside_circle(
+ cx: float, cy: float, r: float
+) -> Callable[[tuple[float, float]], bool]: ...
+def get_cos_sin(x0: float, y0: float, x1: float, y1: float) -> tuple[float, float]: ...
+def check_if_parallel(
+ dx1: float, dy1: float, dx2: float, dy2: float, tolerance: float = ...
+) -> Literal[-1, False, 1]: ...
+def get_parallels(
+ bezier2: ArrayLike, width: float
+) -> tuple[list[tuple[float, float]], list[tuple[float, float]]]: ...
+def find_control_points(
+ c1x: float, c1y: float, mmx: float, mmy: float, c2x: float, c2y: float
+) -> list[tuple[float, float]]: ...
+def make_wedged_bezier2(
+ bezier2: ArrayLike, width: float, w1: float = ..., wm: float = ..., w2: float = ...
+) -> tuple[list[tuple[float, float]], list[tuple[float, float]]]: ...
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/category.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/category.py
new file mode 100644
index 0000000000000000000000000000000000000000..225c837006f726aa97b990c82a3265ec06e55df3
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/category.py
@@ -0,0 +1,235 @@
+"""
+Plotting of string "category" data: ``plot(['d', 'f', 'a'], [1, 2, 3])`` will
+plot three points with x-axis values of 'd', 'f', 'a'.
+
+See :doc:`/gallery/lines_bars_and_markers/categorical_variables` for an
+example.
+
+The module uses Matplotlib's `matplotlib.units` mechanism to convert from
+strings to integers and provides a tick locator, a tick formatter, and the
+`.UnitData` class that creates and stores the string-to-integer mapping.
+"""
+
+from collections import OrderedDict
+import dateutil.parser
+import itertools
+import logging
+
+import numpy as np
+
+from matplotlib import _api, cbook, ticker, units
+
+
+_log = logging.getLogger(__name__)
+
+
+class StrCategoryConverter(units.ConversionInterface):
+ @staticmethod
+ def convert(value, unit, axis):
+ """
+ Convert strings in *value* to floats using mapping information stored
+ in the *unit* object.
+
+ Parameters
+ ----------
+ value : str or iterable
+ Value or list of values to be converted.
+ unit : `.UnitData`
+ An object mapping strings to integers.
+ axis : `~matplotlib.axis.Axis`
+ The axis on which the converted value is plotted.
+
+ .. note:: *axis* is unused.
+
+ Returns
+ -------
+ float or `~numpy.ndarray` of float
+ """
+ if unit is None:
+ raise ValueError(
+ 'Missing category information for StrCategoryConverter; '
+ 'this might be caused by unintendedly mixing categorical and '
+ 'numeric data')
+ StrCategoryConverter._validate_unit(unit)
+ # dtype = object preserves numerical pass throughs
+ values = np.atleast_1d(np.array(value, dtype=object))
+ # force an update so it also does type checking
+ unit.update(values)
+ s = np.vectorize(unit._mapping.__getitem__, otypes=[float])(values)
+ return s if not cbook.is_scalar_or_string(value) else s[0]
+
+ @staticmethod
+ def axisinfo(unit, axis):
+ """
+ Set the default axis ticks and labels.
+
+ Parameters
+ ----------
+ unit : `.UnitData`
+ object string unit information for value
+ axis : `~matplotlib.axis.Axis`
+ axis for which information is being set
+
+ .. note:: *axis* is not used
+
+ Returns
+ -------
+ `~matplotlib.units.AxisInfo`
+ Information to support default tick labeling
+
+ """
+ StrCategoryConverter._validate_unit(unit)
+ # locator and formatter take mapping dict because
+ # args need to be pass by reference for updates
+ majloc = StrCategoryLocator(unit._mapping)
+ majfmt = StrCategoryFormatter(unit._mapping)
+ return units.AxisInfo(majloc=majloc, majfmt=majfmt)
+
+ @staticmethod
+ def default_units(data, axis):
+ """
+ Set and update the `~matplotlib.axis.Axis` units.
+
+ Parameters
+ ----------
+ data : str or iterable of str
+ axis : `~matplotlib.axis.Axis`
+ axis on which the data is plotted
+
+ Returns
+ -------
+ `.UnitData`
+ object storing string to integer mapping
+ """
+ # the conversion call stack is default_units -> axis_info -> convert
+ if axis.units is None:
+ axis.set_units(UnitData(data))
+ else:
+ axis.units.update(data)
+ return axis.units
+
+ @staticmethod
+ def _validate_unit(unit):
+ if not hasattr(unit, '_mapping'):
+ raise ValueError(
+ f'Provided unit "{unit}" is not valid for a categorical '
+ 'converter, as it does not have a _mapping attribute.')
+
+
+class StrCategoryLocator(ticker.Locator):
+ """Tick at every integer mapping of the string data."""
+ def __init__(self, units_mapping):
+ """
+ Parameters
+ ----------
+ units_mapping : dict
+ Mapping of category names (str) to indices (int).
+ """
+ self._units = units_mapping
+
+ def __call__(self):
+ # docstring inherited
+ return list(self._units.values())
+
+ def tick_values(self, vmin, vmax):
+ # docstring inherited
+ return self()
+
+
+class StrCategoryFormatter(ticker.Formatter):
+ """String representation of the data at every tick."""
+ def __init__(self, units_mapping):
+ """
+ Parameters
+ ----------
+ units_mapping : dict
+ Mapping of category names (str) to indices (int).
+ """
+ self._units = units_mapping
+
+ def __call__(self, x, pos=None):
+ # docstring inherited
+ return self.format_ticks([x])[0]
+
+ def format_ticks(self, values):
+ # docstring inherited
+ r_mapping = {v: self._text(k) for k, v in self._units.items()}
+ return [r_mapping.get(round(val), '') for val in values]
+
+ @staticmethod
+ def _text(value):
+ """Convert text values into utf-8 or ascii strings."""
+ if isinstance(value, bytes):
+ value = value.decode(encoding='utf-8')
+ elif not isinstance(value, str):
+ value = str(value)
+ return value
+
+
+class UnitData:
+ def __init__(self, data=None):
+ """
+ Create mapping between unique categorical values and integer ids.
+
+ Parameters
+ ----------
+ data : iterable
+ sequence of string values
+ """
+ self._mapping = OrderedDict()
+ self._counter = itertools.count()
+ if data is not None:
+ self.update(data)
+
+ @staticmethod
+ def _str_is_convertible(val):
+ """
+ Helper method to check whether a string can be parsed as float or date.
+ """
+ try:
+ float(val)
+ except ValueError:
+ try:
+ dateutil.parser.parse(val)
+ except (ValueError, TypeError):
+ # TypeError if dateutil >= 2.8.1 else ValueError
+ return False
+ return True
+
+ def update(self, data):
+ """
+ Map new values to integer identifiers.
+
+ Parameters
+ ----------
+ data : iterable of str or bytes
+
+ Raises
+ ------
+ TypeError
+ If elements in *data* are neither str nor bytes.
+ """
+ data = np.atleast_1d(np.array(data, dtype=object))
+ # check if convertible to number:
+ convertible = True
+ for val in OrderedDict.fromkeys(data):
+ # OrderedDict just iterates over unique values in data.
+ _api.check_isinstance((str, bytes), value=val)
+ if convertible:
+ # this will only be called so long as convertible is True.
+ convertible = self._str_is_convertible(val)
+ if val not in self._mapping:
+ self._mapping[val] = next(self._counter)
+ if data.size and convertible:
+ _log.info('Using categorical units to plot a list of strings '
+ 'that are all parsable as floats or dates. If these '
+ 'strings should be plotted as numbers, cast to the '
+ 'appropriate data type before plotting.')
+
+
+# Register the converter with Matplotlib's unit framework
+# Intentionally set to a single instance
+units.registry[str] = \
+ units.registry[np.str_] = \
+ units.registry[bytes] = \
+ units.registry[np.bytes_] = StrCategoryConverter()
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/cbook.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/cbook.py
new file mode 100644
index 0000000000000000000000000000000000000000..d2ad5fd8cbf7d8eef42f2e70429aa658ff821169
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/cbook.py
@@ -0,0 +1,2419 @@
+"""
+A collection of utility functions and classes. Originally, many
+(but not all) were from the Python Cookbook -- hence the name cbook.
+"""
+
+import collections
+import collections.abc
+import contextlib
+import functools
+import gzip
+import itertools
+import math
+import operator
+import os
+from pathlib import Path
+import shlex
+import subprocess
+import sys
+import time
+import traceback
+import types
+import weakref
+
+import numpy as np
+
+try:
+ from numpy.exceptions import VisibleDeprecationWarning # numpy >= 1.25
+except ImportError:
+ from numpy import VisibleDeprecationWarning
+
+import matplotlib
+from matplotlib import _api, _c_internal_utils
+
+
+class _ExceptionInfo:
+ """
+ A class to carry exception information around.
+
+ This is used to store and later raise exceptions. It's an alternative to
+ directly storing Exception instances that circumvents traceback-related
+ issues: caching tracebacks can keep user's objects in local namespaces
+ alive indefinitely, which can lead to very surprising memory issues for
+ users and result in incorrect tracebacks.
+ """
+
+ def __init__(self, cls, *args):
+ self._cls = cls
+ self._args = args
+
+ @classmethod
+ def from_exception(cls, exc):
+ return cls(type(exc), *exc.args)
+
+ def to_exception(self):
+ return self._cls(*self._args)
+
+
+def _get_running_interactive_framework():
+ """
+ Return the interactive framework whose event loop is currently running, if
+ any, or "headless" if no event loop can be started, or None.
+
+ Returns
+ -------
+ Optional[str]
+ One of the following values: "qt", "gtk3", "gtk4", "wx", "tk",
+ "macosx", "headless", ``None``.
+ """
+ # Use ``sys.modules.get(name)`` rather than ``name in sys.modules`` as
+ # entries can also have been explicitly set to None.
+ QtWidgets = (
+ sys.modules.get("PyQt6.QtWidgets")
+ or sys.modules.get("PySide6.QtWidgets")
+ or sys.modules.get("PyQt5.QtWidgets")
+ or sys.modules.get("PySide2.QtWidgets")
+ )
+ if QtWidgets and QtWidgets.QApplication.instance():
+ return "qt"
+ Gtk = sys.modules.get("gi.repository.Gtk")
+ if Gtk:
+ if Gtk.MAJOR_VERSION == 4:
+ from gi.repository import GLib
+ if GLib.main_depth():
+ return "gtk4"
+ if Gtk.MAJOR_VERSION == 3 and Gtk.main_level():
+ return "gtk3"
+ wx = sys.modules.get("wx")
+ if wx and wx.GetApp():
+ return "wx"
+ tkinter = sys.modules.get("tkinter")
+ if tkinter:
+ codes = {tkinter.mainloop.__code__, tkinter.Misc.mainloop.__code__}
+ for frame in sys._current_frames().values():
+ while frame:
+ if frame.f_code in codes:
+ return "tk"
+ frame = frame.f_back
+ # Preemptively break reference cycle between locals and the frame.
+ del frame
+ macosx = sys.modules.get("matplotlib.backends._macosx")
+ if macosx and macosx.event_loop_is_running():
+ return "macosx"
+ if not _c_internal_utils.display_is_valid():
+ return "headless"
+ return None
+
+
+def _exception_printer(exc):
+ if _get_running_interactive_framework() in ["headless", None]:
+ raise exc
+ else:
+ traceback.print_exc()
+
+
+class _StrongRef:
+ """
+ Wrapper similar to a weakref, but keeping a strong reference to the object.
+ """
+
+ def __init__(self, obj):
+ self._obj = obj
+
+ def __call__(self):
+ return self._obj
+
+ def __eq__(self, other):
+ return isinstance(other, _StrongRef) and self._obj == other._obj
+
+ def __hash__(self):
+ return hash(self._obj)
+
+
+def _weak_or_strong_ref(func, callback):
+ """
+ Return a `WeakMethod` wrapping *func* if possible, else a `_StrongRef`.
+ """
+ try:
+ return weakref.WeakMethod(func, callback)
+ except TypeError:
+ return _StrongRef(func)
+
+
+class _UnhashDict:
+ """
+ A minimal dict-like class that also supports unhashable keys, storing them
+ in a list of key-value pairs.
+
+ This class only implements the interface needed for `CallbackRegistry`, and
+ tries to minimize the overhead for the hashable case.
+ """
+
+ def __init__(self, pairs):
+ self._dict = {}
+ self._pairs = []
+ for k, v in pairs:
+ self[k] = v
+
+ def __setitem__(self, key, value):
+ try:
+ self._dict[key] = value
+ except TypeError:
+ for i, (k, v) in enumerate(self._pairs):
+ if k == key:
+ self._pairs[i] = (key, value)
+ break
+ else:
+ self._pairs.append((key, value))
+
+ def __getitem__(self, key):
+ try:
+ return self._dict[key]
+ except TypeError:
+ pass
+ for k, v in self._pairs:
+ if k == key:
+ return v
+ raise KeyError(key)
+
+ def pop(self, key, *args):
+ try:
+ if key in self._dict:
+ return self._dict.pop(key)
+ except TypeError:
+ for i, (k, v) in enumerate(self._pairs):
+ if k == key:
+ del self._pairs[i]
+ return v
+ if args:
+ return args[0]
+ raise KeyError(key)
+
+ def __iter__(self):
+ yield from self._dict
+ for k, v in self._pairs:
+ yield k
+
+
+class CallbackRegistry:
+ """
+ Handle registering, processing, blocking, and disconnecting
+ for a set of signals and callbacks:
+
+ >>> def oneat(x):
+ ... print('eat', x)
+ >>> def ondrink(x):
+ ... print('drink', x)
+
+ >>> from matplotlib.cbook import CallbackRegistry
+ >>> callbacks = CallbackRegistry()
+
+ >>> id_eat = callbacks.connect('eat', oneat)
+ >>> id_drink = callbacks.connect('drink', ondrink)
+
+ >>> callbacks.process('drink', 123)
+ drink 123
+ >>> callbacks.process('eat', 456)
+ eat 456
+ >>> callbacks.process('be merry', 456) # nothing will be called
+
+ >>> callbacks.disconnect(id_eat)
+ >>> callbacks.process('eat', 456) # nothing will be called
+
+ >>> with callbacks.blocked(signal='drink'):
+ ... callbacks.process('drink', 123) # nothing will be called
+ >>> callbacks.process('drink', 123)
+ drink 123
+
+ In practice, one should always disconnect all callbacks when they are
+ no longer needed to avoid dangling references (and thus memory leaks).
+ However, real code in Matplotlib rarely does so, and due to its design,
+ it is rather difficult to place this kind of code. To get around this,
+ and prevent this class of memory leaks, we instead store weak references
+ to bound methods only, so when the destination object needs to die, the
+ CallbackRegistry won't keep it alive.
+
+ Parameters
+ ----------
+ exception_handler : callable, optional
+ If not None, *exception_handler* must be a function that takes an
+ `Exception` as single parameter. It gets called with any `Exception`
+ raised by the callbacks during `CallbackRegistry.process`, and may
+ either re-raise the exception or handle it in another manner.
+
+ The default handler prints the exception (with `traceback.print_exc`) if
+ an interactive event loop is running; it re-raises the exception if no
+ interactive event loop is running.
+
+ signals : list, optional
+ If not None, *signals* is a list of signals that this registry handles:
+ attempting to `process` or to `connect` to a signal not in the list
+ throws a `ValueError`. The default, None, does not restrict the
+ handled signals.
+ """
+
+ # We maintain two mappings:
+ # callbacks: signal -> {cid -> weakref-to-callback}
+ # _func_cid_map: {(signal, weakref-to-callback) -> cid}
+
+ def __init__(self, exception_handler=_exception_printer, *, signals=None):
+ self._signals = None if signals is None else list(signals) # Copy it.
+ self.exception_handler = exception_handler
+ self.callbacks = {}
+ self._cid_gen = itertools.count()
+ self._func_cid_map = _UnhashDict([])
+ # A hidden variable that marks cids that need to be pickled.
+ self._pickled_cids = set()
+
+ def __getstate__(self):
+ return {
+ **vars(self),
+ # In general, callbacks may not be pickled, so we just drop them,
+ # unless directed otherwise by self._pickled_cids.
+ "callbacks": {s: {cid: proxy() for cid, proxy in d.items()
+ if cid in self._pickled_cids}
+ for s, d in self.callbacks.items()},
+ # It is simpler to reconstruct this from callbacks in __setstate__.
+ "_func_cid_map": None,
+ "_cid_gen": next(self._cid_gen)
+ }
+
+ def __setstate__(self, state):
+ cid_count = state.pop('_cid_gen')
+ vars(self).update(state)
+ self.callbacks = {
+ s: {cid: _weak_or_strong_ref(func, functools.partial(self._remove_proxy, s))
+ for cid, func in d.items()}
+ for s, d in self.callbacks.items()}
+ self._func_cid_map = _UnhashDict(
+ ((s, proxy), cid)
+ for s, d in self.callbacks.items() for cid, proxy in d.items())
+ self._cid_gen = itertools.count(cid_count)
+
+ def connect(self, signal, func):
+ """Register *func* to be called when signal *signal* is generated."""
+ if self._signals is not None:
+ _api.check_in_list(self._signals, signal=signal)
+ proxy = _weak_or_strong_ref(func, functools.partial(self._remove_proxy, signal))
+ try:
+ return self._func_cid_map[signal, proxy]
+ except KeyError:
+ cid = self._func_cid_map[signal, proxy] = next(self._cid_gen)
+ self.callbacks.setdefault(signal, {})[cid] = proxy
+ return cid
+
+ def _connect_picklable(self, signal, func):
+ """
+ Like `.connect`, but the callback is kept when pickling/unpickling.
+
+ Currently internal-use only.
+ """
+ cid = self.connect(signal, func)
+ self._pickled_cids.add(cid)
+ return cid
+
+ # Keep a reference to sys.is_finalizing, as sys may have been cleared out
+ # at that point.
+ def _remove_proxy(self, signal, proxy, *, _is_finalizing=sys.is_finalizing):
+ if _is_finalizing():
+ # Weakrefs can't be properly torn down at that point anymore.
+ return
+ cid = self._func_cid_map.pop((signal, proxy), None)
+ if cid is not None:
+ del self.callbacks[signal][cid]
+ self._pickled_cids.discard(cid)
+ else: # Not found
+ return
+ if len(self.callbacks[signal]) == 0: # Clean up empty dicts
+ del self.callbacks[signal]
+
+ def disconnect(self, cid):
+ """
+ Disconnect the callback registered with callback id *cid*.
+
+ No error is raised if such a callback does not exist.
+ """
+ self._pickled_cids.discard(cid)
+ for signal, proxy in self._func_cid_map:
+ if self._func_cid_map[signal, proxy] == cid:
+ break
+ else: # Not found
+ return
+ assert self.callbacks[signal][cid] == proxy
+ del self.callbacks[signal][cid]
+ self._func_cid_map.pop((signal, proxy))
+ if len(self.callbacks[signal]) == 0: # Clean up empty dicts
+ del self.callbacks[signal]
+
+ def process(self, s, *args, **kwargs):
+ """
+ Process signal *s*.
+
+ All of the functions registered to receive callbacks on *s* will be
+ called with ``*args`` and ``**kwargs``.
+ """
+ if self._signals is not None:
+ _api.check_in_list(self._signals, signal=s)
+ for ref in list(self.callbacks.get(s, {}).values()):
+ func = ref()
+ if func is not None:
+ try:
+ func(*args, **kwargs)
+ # this does not capture KeyboardInterrupt, SystemExit,
+ # and GeneratorExit
+ except Exception as exc:
+ if self.exception_handler is not None:
+ self.exception_handler(exc)
+ else:
+ raise
+
+ @contextlib.contextmanager
+ def blocked(self, *, signal=None):
+ """
+ Block callback signals from being processed.
+
+ A context manager to temporarily block/disable callback signals
+ from being processed by the registered listeners.
+
+ Parameters
+ ----------
+ signal : str, optional
+ The callback signal to block. The default is to block all signals.
+ """
+ orig = self.callbacks
+ try:
+ if signal is None:
+ # Empty out the callbacks
+ self.callbacks = {}
+ else:
+ # Only remove the specific signal
+ self.callbacks = {k: orig[k] for k in orig if k != signal}
+ yield
+ finally:
+ self.callbacks = orig
+
+
+class silent_list(list):
+ """
+ A list with a short ``repr()``.
+
+ This is meant to be used for a homogeneous list of artists, so that they
+ don't cause long, meaningless output.
+
+ Instead of ::
+
+ [,
+ ,
+ ]
+
+ one will get ::
+
+
+
+ If ``self.type`` is None, the type name is obtained from the first item in
+ the list (if any).
+ """
+
+ def __init__(self, type, seq=None):
+ self.type = type
+ if seq is not None:
+ self.extend(seq)
+
+ def __repr__(self):
+ if self.type is not None or len(self) != 0:
+ tp = self.type if self.type is not None else type(self[0]).__name__
+ return f" "
+ else:
+ return ""
+
+
+def _local_over_kwdict(
+ local_var, kwargs, *keys,
+ warning_cls=_api.MatplotlibDeprecationWarning):
+ out = local_var
+ for key in keys:
+ kwarg_val = kwargs.pop(key, None)
+ if kwarg_val is not None:
+ if out is None:
+ out = kwarg_val
+ else:
+ _api.warn_external(f'"{key}" keyword argument will be ignored',
+ warning_cls)
+ return out
+
+
+def strip_math(s):
+ """
+ Remove latex formatting from mathtext.
+
+ Only handles fully math and fully non-math strings.
+ """
+ if len(s) >= 2 and s[0] == s[-1] == "$":
+ s = s[1:-1]
+ for tex, plain in [
+ (r"\times", "x"), # Specifically for Formatter support.
+ (r"\mathdefault", ""),
+ (r"\rm", ""),
+ (r"\cal", ""),
+ (r"\tt", ""),
+ (r"\it", ""),
+ ("\\", ""),
+ ("{", ""),
+ ("}", ""),
+ ]:
+ s = s.replace(tex, plain)
+ return s
+
+
+def _strip_comment(s):
+ """Strip everything from the first unquoted #."""
+ pos = 0
+ while True:
+ quote_pos = s.find('"', pos)
+ hash_pos = s.find('#', pos)
+ if quote_pos < 0:
+ without_comment = s if hash_pos < 0 else s[:hash_pos]
+ return without_comment.strip()
+ elif 0 <= hash_pos < quote_pos:
+ return s[:hash_pos].strip()
+ else:
+ closing_quote_pos = s.find('"', quote_pos + 1)
+ if closing_quote_pos < 0:
+ raise ValueError(
+ f"Missing closing quote in: {s!r}. If you need a double-"
+ 'quote inside a string, use escaping: e.g. "the \" char"')
+ pos = closing_quote_pos + 1 # behind closing quote
+
+
+def is_writable_file_like(obj):
+ """Return whether *obj* looks like a file object with a *write* method."""
+ return callable(getattr(obj, 'write', None))
+
+
+def file_requires_unicode(x):
+ """
+ Return whether the given writable file-like object requires Unicode to be
+ written to it.
+ """
+ try:
+ x.write(b'')
+ except TypeError:
+ return True
+ else:
+ return False
+
+
+def to_filehandle(fname, flag='r', return_opened=False, encoding=None):
+ """
+ Convert a path to an open file handle or pass-through a file-like object.
+
+ Consider using `open_file_cm` instead, as it allows one to properly close
+ newly created file objects more easily.
+
+ Parameters
+ ----------
+ fname : str or path-like or file-like
+ If `str` or `os.PathLike`, the file is opened using the flags specified
+ by *flag* and *encoding*. If a file-like object, it is passed through.
+ flag : str, default: 'r'
+ Passed as the *mode* argument to `open` when *fname* is `str` or
+ `os.PathLike`; ignored if *fname* is file-like.
+ return_opened : bool, default: False
+ If True, return both the file object and a boolean indicating whether
+ this was a new file (that the caller needs to close). If False, return
+ only the new file.
+ encoding : str or None, default: None
+ Passed as the *mode* argument to `open` when *fname* is `str` or
+ `os.PathLike`; ignored if *fname* is file-like.
+
+ Returns
+ -------
+ fh : file-like
+ opened : bool
+ *opened* is only returned if *return_opened* is True.
+ """
+ if isinstance(fname, os.PathLike):
+ fname = os.fspath(fname)
+ if isinstance(fname, str):
+ if fname.endswith('.gz'):
+ fh = gzip.open(fname, flag)
+ elif fname.endswith('.bz2'):
+ # python may not be compiled with bz2 support,
+ # bury import until we need it
+ import bz2
+ fh = bz2.BZ2File(fname, flag)
+ else:
+ fh = open(fname, flag, encoding=encoding)
+ opened = True
+ elif hasattr(fname, 'seek'):
+ fh = fname
+ opened = False
+ else:
+ raise ValueError('fname must be a PathLike or file handle')
+ if return_opened:
+ return fh, opened
+ return fh
+
+
+def open_file_cm(path_or_file, mode="r", encoding=None):
+ r"""Pass through file objects and context-manage path-likes."""
+ fh, opened = to_filehandle(path_or_file, mode, True, encoding)
+ return fh if opened else contextlib.nullcontext(fh)
+
+
+def is_scalar_or_string(val):
+ """Return whether the given object is a scalar or string like."""
+ return isinstance(val, str) or not np.iterable(val)
+
+
+def get_sample_data(fname, asfileobj=True):
+ """
+ Return a sample data file. *fname* is a path relative to the
+ :file:`mpl-data/sample_data` directory. If *asfileobj* is `True`
+ return a file object, otherwise just a file path.
+
+ Sample data files are stored in the 'mpl-data/sample_data' directory within
+ the Matplotlib package.
+
+ If the filename ends in .gz, the file is implicitly ungzipped. If the
+ filename ends with .npy or .npz, and *asfileobj* is `True`, the file is
+ loaded with `numpy.load`.
+ """
+ path = _get_data_path('sample_data', fname)
+ if asfileobj:
+ suffix = path.suffix.lower()
+ if suffix == '.gz':
+ return gzip.open(path)
+ elif suffix in ['.npy', '.npz']:
+ return np.load(path)
+ elif suffix in ['.csv', '.xrc', '.txt']:
+ return path.open('r')
+ else:
+ return path.open('rb')
+ else:
+ return str(path)
+
+
+def _get_data_path(*args):
+ """
+ Return the `pathlib.Path` to a resource file provided by Matplotlib.
+
+ ``*args`` specify a path relative to the base data path.
+ """
+ return Path(matplotlib.get_data_path(), *args)
+
+
+def flatten(seq, scalarp=is_scalar_or_string):
+ """
+ Return a generator of flattened nested containers.
+
+ For example:
+
+ >>> from matplotlib.cbook import flatten
+ >>> l = (('John', ['Hunter']), (1, 23), [[([42, (5, 23)], )]])
+ >>> print(list(flatten(l)))
+ ['John', 'Hunter', 1, 23, 42, 5, 23]
+
+ By: Composite of Holger Krekel and Luther Blissett
+ From: https://code.activestate.com/recipes/121294-simple-generator-for-flattening-nested-containers/
+ and Recipe 1.12 in cookbook
+ """ # noqa: E501
+ for item in seq:
+ if scalarp(item) or item is None:
+ yield item
+ else:
+ yield from flatten(item, scalarp)
+
+
+class _Stack:
+ """
+ Stack of elements with a movable cursor.
+
+ Mimics home/back/forward in a web browser.
+ """
+
+ def __init__(self):
+ self._pos = -1
+ self._elements = []
+
+ def clear(self):
+ """Empty the stack."""
+ self._pos = -1
+ self._elements = []
+
+ def __call__(self):
+ """Return the current element, or None."""
+ return self._elements[self._pos] if self._elements else None
+
+ def __len__(self):
+ return len(self._elements)
+
+ def __getitem__(self, ind):
+ return self._elements[ind]
+
+ def forward(self):
+ """Move the position forward and return the current element."""
+ self._pos = min(self._pos + 1, len(self._elements) - 1)
+ return self()
+
+ def back(self):
+ """Move the position back and return the current element."""
+ self._pos = max(self._pos - 1, 0)
+ return self()
+
+ def push(self, o):
+ """
+ Push *o* to the stack after the current position, and return *o*.
+
+ Discard all later elements.
+ """
+ self._elements[self._pos + 1:] = [o]
+ self._pos = len(self._elements) - 1
+ return o
+
+ def home(self):
+ """
+ Push the first element onto the top of the stack.
+
+ The first element is returned.
+ """
+ return self.push(self._elements[0]) if self._elements else None
+
+
+def safe_masked_invalid(x, copy=False):
+ x = np.array(x, subok=True, copy=copy)
+ if not x.dtype.isnative:
+ # If we have already made a copy, do the byteswap in place, else make a
+ # copy with the byte order swapped.
+ # Swap to native order.
+ x = x.byteswap(inplace=copy).view(x.dtype.newbyteorder('N'))
+ try:
+ xm = np.ma.masked_where(~(np.isfinite(x)), x, copy=False)
+ except TypeError:
+ return x
+ return xm
+
+
+def print_cycles(objects, outstream=sys.stdout, show_progress=False):
+ """
+ Print loops of cyclic references in the given *objects*.
+
+ It is often useful to pass in ``gc.garbage`` to find the cycles that are
+ preventing some objects from being garbage collected.
+
+ Parameters
+ ----------
+ objects
+ A list of objects to find cycles in.
+ outstream
+ The stream for output.
+ show_progress : bool
+ If True, print the number of objects reached as they are found.
+ """
+ import gc
+
+ def print_path(path):
+ for i, step in enumerate(path):
+ # next "wraps around"
+ next = path[(i + 1) % len(path)]
+
+ outstream.write(" %s -- " % type(step))
+ if isinstance(step, dict):
+ for key, val in step.items():
+ if val is next:
+ outstream.write(f"[{key!r}]")
+ break
+ if key is next:
+ outstream.write(f"[key] = {val!r}")
+ break
+ elif isinstance(step, list):
+ outstream.write("[%d]" % step.index(next))
+ elif isinstance(step, tuple):
+ outstream.write("( tuple )")
+ else:
+ outstream.write(repr(step))
+ outstream.write(" ->\n")
+ outstream.write("\n")
+
+ def recurse(obj, start, all, current_path):
+ if show_progress:
+ outstream.write("%d\r" % len(all))
+
+ all[id(obj)] = None
+
+ referents = gc.get_referents(obj)
+ for referent in referents:
+ # If we've found our way back to the start, this is
+ # a cycle, so print it out
+ if referent is start:
+ print_path(current_path)
+
+ # Don't go back through the original list of objects, or
+ # through temporary references to the object, since those
+ # are just an artifact of the cycle detector itself.
+ elif referent is objects or isinstance(referent, types.FrameType):
+ continue
+
+ # We haven't seen this object before, so recurse
+ elif id(referent) not in all:
+ recurse(referent, start, all, current_path + [obj])
+
+ for obj in objects:
+ outstream.write(f"Examining: {obj!r}\n")
+ recurse(obj, obj, {}, [])
+
+
+class Grouper:
+ """
+ A disjoint-set data structure.
+
+ Objects can be joined using :meth:`join`, tested for connectedness
+ using :meth:`joined`, and all disjoint sets can be retrieved by
+ using the object as an iterator.
+
+ The objects being joined must be hashable and weak-referenceable.
+
+ Examples
+ --------
+ >>> from matplotlib.cbook import Grouper
+ >>> class Foo:
+ ... def __init__(self, s):
+ ... self.s = s
+ ... def __repr__(self):
+ ... return self.s
+ ...
+ >>> a, b, c, d, e, f = [Foo(x) for x in 'abcdef']
+ >>> grp = Grouper()
+ >>> grp.join(a, b)
+ >>> grp.join(b, c)
+ >>> grp.join(d, e)
+ >>> list(grp)
+ [[a, b, c], [d, e]]
+ >>> grp.joined(a, b)
+ True
+ >>> grp.joined(a, c)
+ True
+ >>> grp.joined(a, d)
+ False
+ """
+
+ def __init__(self, init=()):
+ self._mapping = weakref.WeakKeyDictionary(
+ {x: weakref.WeakSet([x]) for x in init})
+ self._ordering = weakref.WeakKeyDictionary()
+ for x in init:
+ if x not in self._ordering:
+ self._ordering[x] = len(self._ordering)
+ self._next_order = len(self._ordering) # Plain int to simplify pickling.
+
+ def __getstate__(self):
+ return {
+ **vars(self),
+ # Convert weak refs to strong ones.
+ "_mapping": {k: set(v) for k, v in self._mapping.items()},
+ "_ordering": {**self._ordering},
+ }
+
+ def __setstate__(self, state):
+ vars(self).update(state)
+ # Convert strong refs to weak ones.
+ self._mapping = weakref.WeakKeyDictionary(
+ {k: weakref.WeakSet(v) for k, v in self._mapping.items()})
+ self._ordering = weakref.WeakKeyDictionary(self._ordering)
+
+ def __contains__(self, item):
+ return item in self._mapping
+
+ def join(self, a, *args):
+ """
+ Join given arguments into the same set. Accepts one or more arguments.
+ """
+ mapping = self._mapping
+ try:
+ set_a = mapping[a]
+ except KeyError:
+ set_a = mapping[a] = weakref.WeakSet([a])
+ self._ordering[a] = self._next_order
+ self._next_order += 1
+ for arg in args:
+ try:
+ set_b = mapping[arg]
+ except KeyError:
+ set_b = mapping[arg] = weakref.WeakSet([arg])
+ self._ordering[arg] = self._next_order
+ self._next_order += 1
+ if set_b is not set_a:
+ if len(set_b) > len(set_a):
+ set_a, set_b = set_b, set_a
+ set_a.update(set_b)
+ for elem in set_b:
+ mapping[elem] = set_a
+
+ def joined(self, a, b):
+ """Return whether *a* and *b* are members of the same set."""
+ return (self._mapping.get(a, object()) is self._mapping.get(b))
+
+ def remove(self, a):
+ """Remove *a* from the grouper, doing nothing if it is not there."""
+ self._mapping.pop(a, {a}).remove(a)
+ self._ordering.pop(a, None)
+
+ def __iter__(self):
+ """
+ Iterate over each of the disjoint sets as a list.
+
+ The iterator is invalid if interleaved with calls to join().
+ """
+ unique_groups = {id(group): group for group in self._mapping.values()}
+ for group in unique_groups.values():
+ yield sorted(group, key=self._ordering.__getitem__)
+
+ def get_siblings(self, a):
+ """Return all of the items joined with *a*, including itself."""
+ siblings = self._mapping.get(a, [a])
+ return sorted(siblings, key=self._ordering.get)
+
+
+class GrouperView:
+ """Immutable view over a `.Grouper`."""
+
+ def __init__(self, grouper): self._grouper = grouper
+ def __contains__(self, item): return item in self._grouper
+ def __iter__(self): return iter(self._grouper)
+
+ def joined(self, a, b):
+ """
+ Return whether *a* and *b* are members of the same set.
+ """
+ return self._grouper.joined(a, b)
+
+ def get_siblings(self, a):
+ """
+ Return all of the items joined with *a*, including itself.
+ """
+ return self._grouper.get_siblings(a)
+
+
+def simple_linear_interpolation(a, steps):
+ """
+ Resample an array with ``steps - 1`` points between original point pairs.
+
+ Along each column of *a*, ``(steps - 1)`` points are introduced between
+ each original values; the values are linearly interpolated.
+
+ Parameters
+ ----------
+ a : array, shape (n, ...)
+ steps : int
+
+ Returns
+ -------
+ array
+ shape ``((n - 1) * steps + 1, ...)``
+ """
+ fps = a.reshape((len(a), -1))
+ xp = np.arange(len(a)) * steps
+ x = np.arange((len(a) - 1) * steps + 1)
+ return (np.column_stack([np.interp(x, xp, fp) for fp in fps.T])
+ .reshape((len(x),) + a.shape[1:]))
+
+
+def delete_masked_points(*args):
+ """
+ Find all masked and/or non-finite points in a set of arguments,
+ and return the arguments with only the unmasked points remaining.
+
+ Arguments can be in any of 5 categories:
+
+ 1) 1-D masked arrays
+ 2) 1-D ndarrays
+ 3) ndarrays with more than one dimension
+ 4) other non-string iterables
+ 5) anything else
+
+ The first argument must be in one of the first four categories;
+ any argument with a length differing from that of the first
+ argument (and hence anything in category 5) then will be
+ passed through unchanged.
+
+ Masks are obtained from all arguments of the correct length
+ in categories 1, 2, and 4; a point is bad if masked in a masked
+ array or if it is a nan or inf. No attempt is made to
+ extract a mask from categories 2, 3, and 4 if `numpy.isfinite`
+ does not yield a Boolean array.
+
+ All input arguments that are not passed unchanged are returned
+ as ndarrays after removing the points or rows corresponding to
+ masks in any of the arguments.
+
+ A vastly simpler version of this function was originally
+ written as a helper for Axes.scatter().
+
+ """
+ if not len(args):
+ return ()
+ if is_scalar_or_string(args[0]):
+ raise ValueError("First argument must be a sequence")
+ nrecs = len(args[0])
+ margs = []
+ seqlist = [False] * len(args)
+ for i, x in enumerate(args):
+ if not isinstance(x, str) and np.iterable(x) and len(x) == nrecs:
+ seqlist[i] = True
+ if isinstance(x, np.ma.MaskedArray):
+ if x.ndim > 1:
+ raise ValueError("Masked arrays must be 1-D")
+ else:
+ x = np.asarray(x)
+ margs.append(x)
+ masks = [] # List of masks that are True where good.
+ for i, x in enumerate(margs):
+ if seqlist[i]:
+ if x.ndim > 1:
+ continue # Don't try to get nan locations unless 1-D.
+ if isinstance(x, np.ma.MaskedArray):
+ masks.append(~np.ma.getmaskarray(x)) # invert the mask
+ xd = x.data
+ else:
+ xd = x
+ try:
+ mask = np.isfinite(xd)
+ if isinstance(mask, np.ndarray):
+ masks.append(mask)
+ except Exception: # Fixme: put in tuple of possible exceptions?
+ pass
+ if len(masks):
+ mask = np.logical_and.reduce(masks)
+ igood = mask.nonzero()[0]
+ if len(igood) < nrecs:
+ for i, x in enumerate(margs):
+ if seqlist[i]:
+ margs[i] = x[igood]
+ for i, x in enumerate(margs):
+ if seqlist[i] and isinstance(x, np.ma.MaskedArray):
+ margs[i] = x.filled()
+ return margs
+
+
+def _combine_masks(*args):
+ """
+ Find all masked and/or non-finite points in a set of arguments,
+ and return the arguments as masked arrays with a common mask.
+
+ Arguments can be in any of 5 categories:
+
+ 1) 1-D masked arrays
+ 2) 1-D ndarrays
+ 3) ndarrays with more than one dimension
+ 4) other non-string iterables
+ 5) anything else
+
+ The first argument must be in one of the first four categories;
+ any argument with a length differing from that of the first
+ argument (and hence anything in category 5) then will be
+ passed through unchanged.
+
+ Masks are obtained from all arguments of the correct length
+ in categories 1, 2, and 4; a point is bad if masked in a masked
+ array or if it is a nan or inf. No attempt is made to
+ extract a mask from categories 2 and 4 if `numpy.isfinite`
+ does not yield a Boolean array. Category 3 is included to
+ support RGB or RGBA ndarrays, which are assumed to have only
+ valid values and which are passed through unchanged.
+
+ All input arguments that are not passed unchanged are returned
+ as masked arrays if any masked points are found, otherwise as
+ ndarrays.
+
+ """
+ if not len(args):
+ return ()
+ if is_scalar_or_string(args[0]):
+ raise ValueError("First argument must be a sequence")
+ nrecs = len(args[0])
+ margs = [] # Output args; some may be modified.
+ seqlist = [False] * len(args) # Flags: True if output will be masked.
+ masks = [] # List of masks.
+ for i, x in enumerate(args):
+ if is_scalar_or_string(x) or len(x) != nrecs:
+ margs.append(x) # Leave it unmodified.
+ else:
+ if isinstance(x, np.ma.MaskedArray) and x.ndim > 1:
+ raise ValueError("Masked arrays must be 1-D")
+ try:
+ x = np.asanyarray(x)
+ except (VisibleDeprecationWarning, ValueError):
+ # NumPy 1.19 raises a warning about ragged arrays, but we want
+ # to accept basically anything here.
+ x = np.asanyarray(x, dtype=object)
+ if x.ndim == 1:
+ x = safe_masked_invalid(x)
+ seqlist[i] = True
+ if np.ma.is_masked(x):
+ masks.append(np.ma.getmaskarray(x))
+ margs.append(x) # Possibly modified.
+ if len(masks):
+ mask = np.logical_or.reduce(masks)
+ for i, x in enumerate(margs):
+ if seqlist[i]:
+ margs[i] = np.ma.array(x, mask=mask)
+ return margs
+
+
+def _broadcast_with_masks(*args, compress=False):
+ """
+ Broadcast inputs, combining all masked arrays.
+
+ Parameters
+ ----------
+ *args : array-like
+ The inputs to broadcast.
+ compress : bool, default: False
+ Whether to compress the masked arrays. If False, the masked values
+ are replaced by NaNs.
+
+ Returns
+ -------
+ list of array-like
+ The broadcasted and masked inputs.
+ """
+ # extract the masks, if any
+ masks = [k.mask for k in args if isinstance(k, np.ma.MaskedArray)]
+ # broadcast to match the shape
+ bcast = np.broadcast_arrays(*args, *masks)
+ inputs = bcast[:len(args)]
+ masks = bcast[len(args):]
+ if masks:
+ # combine the masks into one
+ mask = np.logical_or.reduce(masks)
+ # put mask on and compress
+ if compress:
+ inputs = [np.ma.array(k, mask=mask).compressed()
+ for k in inputs]
+ else:
+ inputs = [np.ma.array(k, mask=mask, dtype=float).filled(np.nan).ravel()
+ for k in inputs]
+ else:
+ inputs = [np.ravel(k) for k in inputs]
+ return inputs
+
+
+def boxplot_stats(X, whis=1.5, bootstrap=None, labels=None, autorange=False):
+ r"""
+ Return a list of dictionaries of statistics used to draw a series of box
+ and whisker plots using `~.Axes.bxp`.
+
+ Parameters
+ ----------
+ X : array-like
+ Data that will be represented in the boxplots. Should have 2 or
+ fewer dimensions.
+
+ whis : float or (float, float), default: 1.5
+ The position of the whiskers.
+
+ If a float, the lower whisker is at the lowest datum above
+ ``Q1 - whis*(Q3-Q1)``, and the upper whisker at the highest datum below
+ ``Q3 + whis*(Q3-Q1)``, where Q1 and Q3 are the first and third
+ quartiles. The default value of ``whis = 1.5`` corresponds to Tukey's
+ original definition of boxplots.
+
+ If a pair of floats, they indicate the percentiles at which to draw the
+ whiskers (e.g., (5, 95)). In particular, setting this to (0, 100)
+ results in whiskers covering the whole range of the data.
+
+ In the edge case where ``Q1 == Q3``, *whis* is automatically set to
+ (0, 100) (cover the whole range of the data) if *autorange* is True.
+
+ Beyond the whiskers, data are considered outliers and are plotted as
+ individual points.
+
+ bootstrap : int, optional
+ Number of times the confidence intervals around the median
+ should be bootstrapped (percentile method).
+
+ labels : list of str, optional
+ Labels for each dataset. Length must be compatible with
+ dimensions of *X*.
+
+ autorange : bool, optional (False)
+ When `True` and the data are distributed such that the 25th and 75th
+ percentiles are equal, ``whis`` is set to (0, 100) such that the
+ whisker ends are at the minimum and maximum of the data.
+
+ Returns
+ -------
+ list of dict
+ A list of dictionaries containing the results for each column
+ of data. Keys of each dictionary are the following:
+
+ ======== ===================================
+ Key Value Description
+ ======== ===================================
+ label tick label for the boxplot
+ mean arithmetic mean value
+ med 50th percentile
+ q1 first quartile (25th percentile)
+ q3 third quartile (75th percentile)
+ iqr interquartile range
+ cilo lower notch around the median
+ cihi upper notch around the median
+ whislo end of the lower whisker
+ whishi end of the upper whisker
+ fliers outliers
+ ======== ===================================
+
+ Notes
+ -----
+ Non-bootstrapping approach to confidence interval uses Gaussian-based
+ asymptotic approximation:
+
+ .. math::
+
+ \mathrm{med} \pm 1.57 \times \frac{\mathrm{iqr}}{\sqrt{N}}
+
+ General approach from:
+ McGill, R., Tukey, J.W., and Larsen, W.A. (1978) "Variations of
+ Boxplots", The American Statistician, 32:12-16.
+ """
+
+ def _bootstrap_median(data, N=5000):
+ # determine 95% confidence intervals of the median
+ M = len(data)
+ percentiles = [2.5, 97.5]
+
+ bs_index = np.random.randint(M, size=(N, M))
+ bsData = data[bs_index]
+ estimate = np.median(bsData, axis=1, overwrite_input=True)
+
+ CI = np.percentile(estimate, percentiles)
+ return CI
+
+ def _compute_conf_interval(data, med, iqr, bootstrap):
+ if bootstrap is not None:
+ # Do a bootstrap estimate of notch locations.
+ # get conf. intervals around median
+ CI = _bootstrap_median(data, N=bootstrap)
+ notch_min = CI[0]
+ notch_max = CI[1]
+ else:
+
+ N = len(data)
+ notch_min = med - 1.57 * iqr / np.sqrt(N)
+ notch_max = med + 1.57 * iqr / np.sqrt(N)
+
+ return notch_min, notch_max
+
+ # output is a list of dicts
+ bxpstats = []
+
+ # convert X to a list of lists
+ X = _reshape_2D(X, "X")
+
+ ncols = len(X)
+ if labels is None:
+ labels = itertools.repeat(None)
+ elif len(labels) != ncols:
+ raise ValueError("Dimensions of labels and X must be compatible")
+
+ input_whis = whis
+ for ii, (x, label) in enumerate(zip(X, labels)):
+
+ # empty dict
+ stats = {}
+ if label is not None:
+ stats['label'] = label
+
+ # restore whis to the input values in case it got changed in the loop
+ whis = input_whis
+
+ # note tricksiness, append up here and then mutate below
+ bxpstats.append(stats)
+
+ # if empty, bail
+ if len(x) == 0:
+ stats['fliers'] = np.array([])
+ stats['mean'] = np.nan
+ stats['med'] = np.nan
+ stats['q1'] = np.nan
+ stats['q3'] = np.nan
+ stats['iqr'] = np.nan
+ stats['cilo'] = np.nan
+ stats['cihi'] = np.nan
+ stats['whislo'] = np.nan
+ stats['whishi'] = np.nan
+ continue
+
+ # up-convert to an array, just to be safe
+ x = np.ma.asarray(x)
+ x = x.data[~x.mask].ravel()
+
+ # arithmetic mean
+ stats['mean'] = np.mean(x)
+
+ # medians and quartiles
+ q1, med, q3 = np.percentile(x, [25, 50, 75])
+
+ # interquartile range
+ stats['iqr'] = q3 - q1
+ if stats['iqr'] == 0 and autorange:
+ whis = (0, 100)
+
+ # conf. interval around median
+ stats['cilo'], stats['cihi'] = _compute_conf_interval(
+ x, med, stats['iqr'], bootstrap
+ )
+
+ # lowest/highest non-outliers
+ if np.iterable(whis) and not isinstance(whis, str):
+ loval, hival = np.percentile(x, whis)
+ elif np.isreal(whis):
+ loval = q1 - whis * stats['iqr']
+ hival = q3 + whis * stats['iqr']
+ else:
+ raise ValueError('whis must be a float or list of percentiles')
+
+ # get high extreme
+ wiskhi = x[x <= hival]
+ if len(wiskhi) == 0 or np.max(wiskhi) < q3:
+ stats['whishi'] = q3
+ else:
+ stats['whishi'] = np.max(wiskhi)
+
+ # get low extreme
+ wisklo = x[x >= loval]
+ if len(wisklo) == 0 or np.min(wisklo) > q1:
+ stats['whislo'] = q1
+ else:
+ stats['whislo'] = np.min(wisklo)
+
+ # compute a single array of outliers
+ stats['fliers'] = np.concatenate([
+ x[x < stats['whislo']],
+ x[x > stats['whishi']],
+ ])
+
+ # add in the remaining stats
+ stats['q1'], stats['med'], stats['q3'] = q1, med, q3
+
+ return bxpstats
+
+
+#: Maps short codes for line style to their full name used by backends.
+ls_mapper = {'-': 'solid', '--': 'dashed', '-.': 'dashdot', ':': 'dotted'}
+#: Maps full names for line styles used by backends to their short codes.
+ls_mapper_r = {v: k for k, v in ls_mapper.items()}
+
+
+def contiguous_regions(mask):
+ """
+ Return a list of (ind0, ind1) such that ``mask[ind0:ind1].all()`` is
+ True and we cover all such regions.
+ """
+ mask = np.asarray(mask, dtype=bool)
+
+ if not mask.size:
+ return []
+
+ # Find the indices of region changes, and correct offset
+ idx, = np.nonzero(mask[:-1] != mask[1:])
+ idx += 1
+
+ # List operations are faster for moderately sized arrays
+ idx = idx.tolist()
+
+ # Add first and/or last index if needed
+ if mask[0]:
+ idx = [0] + idx
+ if mask[-1]:
+ idx.append(len(mask))
+
+ return list(zip(idx[::2], idx[1::2]))
+
+
+def is_math_text(s):
+ """
+ Return whether the string *s* contains math expressions.
+
+ This is done by checking whether *s* contains an even number of
+ non-escaped dollar signs.
+ """
+ s = str(s)
+ dollar_count = s.count(r'$') - s.count(r'\$')
+ even_dollars = (dollar_count > 0 and dollar_count % 2 == 0)
+ return even_dollars
+
+
+def _to_unmasked_float_array(x):
+ """
+ Convert a sequence to a float array; if input was a masked array, masked
+ values are converted to nans.
+ """
+ if hasattr(x, 'mask'):
+ return np.ma.asarray(x, float).filled(np.nan)
+ else:
+ return np.asarray(x, float)
+
+
+def _check_1d(x):
+ """Convert scalars to 1D arrays; pass-through arrays as is."""
+ # Unpack in case of e.g. Pandas or xarray object
+ x = _unpack_to_numpy(x)
+ # plot requires `shape` and `ndim`. If passed an
+ # object that doesn't provide them, then force to numpy array.
+ # Note this will strip unit information.
+ if (not hasattr(x, 'shape') or
+ not hasattr(x, 'ndim') or
+ len(x.shape) < 1):
+ return np.atleast_1d(x)
+ else:
+ return x
+
+
+def _reshape_2D(X, name):
+ """
+ Use Fortran ordering to convert ndarrays and lists of iterables to lists of
+ 1D arrays.
+
+ Lists of iterables are converted by applying `numpy.asanyarray` to each of
+ their elements. 1D ndarrays are returned in a singleton list containing
+ them. 2D ndarrays are converted to the list of their *columns*.
+
+ *name* is used to generate the error message for invalid inputs.
+ """
+
+ # Unpack in case of e.g. Pandas or xarray object
+ X = _unpack_to_numpy(X)
+
+ # Iterate over columns for ndarrays.
+ if isinstance(X, np.ndarray):
+ X = X.transpose()
+
+ if len(X) == 0:
+ return [[]]
+ elif X.ndim == 1 and np.ndim(X[0]) == 0:
+ # 1D array of scalars: directly return it.
+ return [X]
+ elif X.ndim in [1, 2]:
+ # 2D array, or 1D array of iterables: flatten them first.
+ return [np.reshape(x, -1) for x in X]
+ else:
+ raise ValueError(f'{name} must have 2 or fewer dimensions')
+
+ # Iterate over list of iterables.
+ if len(X) == 0:
+ return [[]]
+
+ result = []
+ is_1d = True
+ for xi in X:
+ # check if this is iterable, except for strings which we
+ # treat as singletons.
+ if not isinstance(xi, str):
+ try:
+ iter(xi)
+ except TypeError:
+ pass
+ else:
+ is_1d = False
+ xi = np.asanyarray(xi)
+ nd = np.ndim(xi)
+ if nd > 1:
+ raise ValueError(f'{name} must have 2 or fewer dimensions')
+ result.append(xi.reshape(-1))
+
+ if is_1d:
+ # 1D array of scalars: directly return it.
+ return [np.reshape(result, -1)]
+ else:
+ # 2D array, or 1D array of iterables: use flattened version.
+ return result
+
+
+def violin_stats(X, method, points=100, quantiles=None):
+ """
+ Return a list of dictionaries of data which can be used to draw a series
+ of violin plots.
+
+ See the ``Returns`` section below to view the required keys of the
+ dictionary.
+
+ Users can skip this function and pass a user-defined set of dictionaries
+ with the same keys to `~.axes.Axes.violinplot` instead of using Matplotlib
+ to do the calculations. See the *Returns* section below for the keys
+ that must be present in the dictionaries.
+
+ Parameters
+ ----------
+ X : array-like
+ Sample data that will be used to produce the gaussian kernel density
+ estimates. Must have 2 or fewer dimensions.
+
+ method : callable
+ The method used to calculate the kernel density estimate for each
+ column of data. When called via ``method(v, coords)``, it should
+ return a vector of the values of the KDE evaluated at the values
+ specified in coords.
+
+ points : int, default: 100
+ Defines the number of points to evaluate each of the gaussian kernel
+ density estimates at.
+
+ quantiles : array-like, default: None
+ Defines (if not None) a list of floats in interval [0, 1] for each
+ column of data, which represents the quantiles that will be rendered
+ for that column of data. Must have 2 or fewer dimensions. 1D array will
+ be treated as a singleton list containing them.
+
+ Returns
+ -------
+ list of dict
+ A list of dictionaries containing the results for each column of data.
+ The dictionaries contain at least the following:
+
+ - coords: A list of scalars containing the coordinates this particular
+ kernel density estimate was evaluated at.
+ - vals: A list of scalars containing the values of the kernel density
+ estimate at each of the coordinates given in *coords*.
+ - mean: The mean value for this column of data.
+ - median: The median value for this column of data.
+ - min: The minimum value for this column of data.
+ - max: The maximum value for this column of data.
+ - quantiles: The quantile values for this column of data.
+ """
+
+ # List of dictionaries describing each of the violins.
+ vpstats = []
+
+ # Want X to be a list of data sequences
+ X = _reshape_2D(X, "X")
+
+ # Want quantiles to be as the same shape as data sequences
+ if quantiles is not None and len(quantiles) != 0:
+ quantiles = _reshape_2D(quantiles, "quantiles")
+ # Else, mock quantiles if it's none or empty
+ else:
+ quantiles = [[]] * len(X)
+
+ # quantiles should have the same size as dataset
+ if len(X) != len(quantiles):
+ raise ValueError("List of violinplot statistics and quantiles values"
+ " must have the same length")
+
+ # Zip x and quantiles
+ for (x, q) in zip(X, quantiles):
+ # Dictionary of results for this distribution
+ stats = {}
+
+ # Calculate basic stats for the distribution
+ min_val = np.min(x)
+ max_val = np.max(x)
+ quantile_val = np.percentile(x, 100 * q)
+
+ # Evaluate the kernel density estimate
+ coords = np.linspace(min_val, max_val, points)
+ stats['vals'] = method(x, coords)
+ stats['coords'] = coords
+
+ # Store additional statistics for this distribution
+ stats['mean'] = np.mean(x)
+ stats['median'] = np.median(x)
+ stats['min'] = min_val
+ stats['max'] = max_val
+ stats['quantiles'] = np.atleast_1d(quantile_val)
+
+ # Append to output
+ vpstats.append(stats)
+
+ return vpstats
+
+
+def pts_to_prestep(x, *args):
+ """
+ Convert continuous line to pre-steps.
+
+ Given a set of ``N`` points, convert to ``2N - 1`` points, which when
+ connected linearly give a step function which changes values at the
+ beginning of the intervals.
+
+ Parameters
+ ----------
+ x : array
+ The x location of the steps. May be empty.
+
+ y1, ..., yp : array
+ y arrays to be turned into steps; all must be the same length as ``x``.
+
+ Returns
+ -------
+ array
+ The x and y values converted to steps in the same order as the input;
+ can be unpacked as ``x_out, y1_out, ..., yp_out``. If the input is
+ length ``N``, each of these arrays will be length ``2N + 1``. For
+ ``N=0``, the length will be 0.
+
+ Examples
+ --------
+ >>> x_s, y1_s, y2_s = pts_to_prestep(x, y1, y2)
+ """
+ steps = np.zeros((1 + len(args), max(2 * len(x) - 1, 0)))
+ # In all `pts_to_*step` functions, only assign once using *x* and *args*,
+ # as converting to an array may be expensive.
+ steps[0, 0::2] = x
+ steps[0, 1::2] = steps[0, 0:-2:2]
+ steps[1:, 0::2] = args
+ steps[1:, 1::2] = steps[1:, 2::2]
+ return steps
+
+
+def pts_to_poststep(x, *args):
+ """
+ Convert continuous line to post-steps.
+
+ Given a set of ``N`` points convert to ``2N + 1`` points, which when
+ connected linearly give a step function which changes values at the end of
+ the intervals.
+
+ Parameters
+ ----------
+ x : array
+ The x location of the steps. May be empty.
+
+ y1, ..., yp : array
+ y arrays to be turned into steps; all must be the same length as ``x``.
+
+ Returns
+ -------
+ array
+ The x and y values converted to steps in the same order as the input;
+ can be unpacked as ``x_out, y1_out, ..., yp_out``. If the input is
+ length ``N``, each of these arrays will be length ``2N + 1``. For
+ ``N=0``, the length will be 0.
+
+ Examples
+ --------
+ >>> x_s, y1_s, y2_s = pts_to_poststep(x, y1, y2)
+ """
+ steps = np.zeros((1 + len(args), max(2 * len(x) - 1, 0)))
+ steps[0, 0::2] = x
+ steps[0, 1::2] = steps[0, 2::2]
+ steps[1:, 0::2] = args
+ steps[1:, 1::2] = steps[1:, 0:-2:2]
+ return steps
+
+
+def pts_to_midstep(x, *args):
+ """
+ Convert continuous line to mid-steps.
+
+ Given a set of ``N`` points convert to ``2N`` points which when connected
+ linearly give a step function which changes values at the middle of the
+ intervals.
+
+ Parameters
+ ----------
+ x : array
+ The x location of the steps. May be empty.
+
+ y1, ..., yp : array
+ y arrays to be turned into steps; all must be the same length as
+ ``x``.
+
+ Returns
+ -------
+ array
+ The x and y values converted to steps in the same order as the input;
+ can be unpacked as ``x_out, y1_out, ..., yp_out``. If the input is
+ length ``N``, each of these arrays will be length ``2N``.
+
+ Examples
+ --------
+ >>> x_s, y1_s, y2_s = pts_to_midstep(x, y1, y2)
+ """
+ steps = np.zeros((1 + len(args), 2 * len(x)))
+ x = np.asanyarray(x)
+ steps[0, 1:-1:2] = steps[0, 2::2] = (x[:-1] + x[1:]) / 2
+ steps[0, :1] = x[:1] # Also works for zero-sized input.
+ steps[0, -1:] = x[-1:]
+ steps[1:, 0::2] = args
+ steps[1:, 1::2] = steps[1:, 0::2]
+ return steps
+
+
+STEP_LOOKUP_MAP = {'default': lambda x, y: (x, y),
+ 'steps': pts_to_prestep,
+ 'steps-pre': pts_to_prestep,
+ 'steps-post': pts_to_poststep,
+ 'steps-mid': pts_to_midstep}
+
+
+def index_of(y):
+ """
+ A helper function to create reasonable x values for the given *y*.
+
+ This is used for plotting (x, y) if x values are not explicitly given.
+
+ First try ``y.index`` (assuming *y* is a `pandas.Series`), if that
+ fails, use ``range(len(y))``.
+
+ This will be extended in the future to deal with more types of
+ labeled data.
+
+ Parameters
+ ----------
+ y : float or array-like
+
+ Returns
+ -------
+ x, y : ndarray
+ The x and y values to plot.
+ """
+ try:
+ return y.index.to_numpy(), y.to_numpy()
+ except AttributeError:
+ pass
+ try:
+ y = _check_1d(y)
+ except (VisibleDeprecationWarning, ValueError):
+ # NumPy 1.19 will warn on ragged input, and we can't actually use it.
+ pass
+ else:
+ return np.arange(y.shape[0], dtype=float), y
+ raise ValueError('Input could not be cast to an at-least-1D NumPy array')
+
+
+def safe_first_element(obj):
+ """
+ Return the first element in *obj*.
+
+ This is a type-independent way of obtaining the first element,
+ supporting both index access and the iterator protocol.
+ """
+ if isinstance(obj, collections.abc.Iterator):
+ # needed to accept `array.flat` as input.
+ # np.flatiter reports as an instance of collections.Iterator but can still be
+ # indexed via []. This has the side effect of re-setting the iterator, but
+ # that is acceptable.
+ try:
+ return obj[0]
+ except TypeError:
+ pass
+ raise RuntimeError("matplotlib does not support generators as input")
+ return next(iter(obj))
+
+
+def _safe_first_finite(obj):
+ """
+ Return the first finite element in *obj* if one is available and skip_nonfinite is
+ True. Otherwise, return the first element.
+
+ This is a method for internal use.
+
+ This is a type-independent way of obtaining the first finite element, supporting
+ both index access and the iterator protocol.
+ """
+ def safe_isfinite(val):
+ if val is None:
+ return False
+ try:
+ return math.isfinite(val)
+ except (TypeError, ValueError):
+ # if the outer object is 2d, then val is a 1d array, and
+ # - math.isfinite(numpy.zeros(3)) raises TypeError
+ # - math.isfinite(torch.zeros(3)) raises ValueError
+ pass
+ try:
+ return np.isfinite(val) if np.isscalar(val) else True
+ except TypeError:
+ # This is something that NumPy cannot make heads or tails of,
+ # assume "finite"
+ return True
+
+ if isinstance(obj, np.flatiter):
+ # TODO do the finite filtering on this
+ return obj[0]
+ elif isinstance(obj, collections.abc.Iterator):
+ raise RuntimeError("matplotlib does not support generators as input")
+ else:
+ for val in obj:
+ if safe_isfinite(val):
+ return val
+ return safe_first_element(obj)
+
+
+def sanitize_sequence(data):
+ """
+ Convert dictview objects to list. Other inputs are returned unchanged.
+ """
+ return (list(data) if isinstance(data, collections.abc.MappingView)
+ else data)
+
+
+def normalize_kwargs(kw, alias_mapping=None):
+ """
+ Helper function to normalize kwarg inputs.
+
+ Parameters
+ ----------
+ kw : dict or None
+ A dict of keyword arguments. None is explicitly supported and treated
+ as an empty dict, to support functions with an optional parameter of
+ the form ``props=None``.
+
+ alias_mapping : dict or Artist subclass or Artist instance, optional
+ A mapping between a canonical name to a list of aliases, in order of
+ precedence from lowest to highest.
+
+ If the canonical value is not in the list it is assumed to have the
+ highest priority.
+
+ If an Artist subclass or instance is passed, use its properties alias
+ mapping.
+
+ Raises
+ ------
+ TypeError
+ To match what Python raises if invalid arguments/keyword arguments are
+ passed to a callable.
+ """
+ from matplotlib.artist import Artist
+
+ if kw is None:
+ return {}
+
+ # deal with default value of alias_mapping
+ if alias_mapping is None:
+ alias_mapping = {}
+ elif (isinstance(alias_mapping, type) and issubclass(alias_mapping, Artist)
+ or isinstance(alias_mapping, Artist)):
+ alias_mapping = getattr(alias_mapping, "_alias_map", {})
+
+ to_canonical = {alias: canonical
+ for canonical, alias_list in alias_mapping.items()
+ for alias in alias_list}
+ canonical_to_seen = {}
+ ret = {} # output dictionary
+
+ for k, v in kw.items():
+ canonical = to_canonical.get(k, k)
+ if canonical in canonical_to_seen:
+ raise TypeError(f"Got both {canonical_to_seen[canonical]!r} and "
+ f"{k!r}, which are aliases of one another")
+ canonical_to_seen[canonical] = k
+ ret[canonical] = v
+
+ return ret
+
+
+@contextlib.contextmanager
+def _lock_path(path):
+ """
+ Context manager for locking a path.
+
+ Usage::
+
+ with _lock_path(path):
+ ...
+
+ Another thread or process that attempts to lock the same path will wait
+ until this context manager is exited.
+
+ The lock is implemented by creating a temporary file in the parent
+ directory, so that directory must exist and be writable.
+ """
+ path = Path(path)
+ lock_path = path.with_name(path.name + ".matplotlib-lock")
+ retries = 50
+ sleeptime = 0.1
+ for _ in range(retries):
+ try:
+ with lock_path.open("xb"):
+ break
+ except FileExistsError:
+ time.sleep(sleeptime)
+ else:
+ raise TimeoutError("""\
+Lock error: Matplotlib failed to acquire the following lock file:
+ {}
+This maybe due to another process holding this lock file. If you are sure no
+other Matplotlib process is running, remove this file and try again.""".format(
+ lock_path))
+ try:
+ yield
+ finally:
+ lock_path.unlink()
+
+
+def _topmost_artist(
+ artists,
+ _cached_max=functools.partial(max, key=operator.attrgetter("zorder"))):
+ """
+ Get the topmost artist of a list.
+
+ In case of a tie, return the *last* of the tied artists, as it will be
+ drawn on top of the others. `max` returns the first maximum in case of
+ ties, so we need to iterate over the list in reverse order.
+ """
+ return _cached_max(reversed(artists))
+
+
+def _str_equal(obj, s):
+ """
+ Return whether *obj* is a string equal to string *s*.
+
+ This helper solely exists to handle the case where *obj* is a numpy array,
+ because in such cases, a naive ``obj == s`` would yield an array, which
+ cannot be used in a boolean context.
+ """
+ return isinstance(obj, str) and obj == s
+
+
+def _str_lower_equal(obj, s):
+ """
+ Return whether *obj* is a string equal, when lowercased, to string *s*.
+
+ This helper solely exists to handle the case where *obj* is a numpy array,
+ because in such cases, a naive ``obj == s`` would yield an array, which
+ cannot be used in a boolean context.
+ """
+ return isinstance(obj, str) and obj.lower() == s
+
+
+def _array_perimeter(arr):
+ """
+ Get the elements on the perimeter of *arr*.
+
+ Parameters
+ ----------
+ arr : ndarray, shape (M, N)
+ The input array.
+
+ Returns
+ -------
+ ndarray, shape (2*(M - 1) + 2*(N - 1),)
+ The elements on the perimeter of the array::
+
+ [arr[0, 0], ..., arr[0, -1], ..., arr[-1, -1], ..., arr[-1, 0], ...]
+
+ Examples
+ --------
+ >>> i, j = np.ogrid[:3, :4]
+ >>> a = i*10 + j
+ >>> a
+ array([[ 0, 1, 2, 3],
+ [10, 11, 12, 13],
+ [20, 21, 22, 23]])
+ >>> _array_perimeter(a)
+ array([ 0, 1, 2, 3, 13, 23, 22, 21, 20, 10])
+ """
+ # note we use Python's half-open ranges to avoid repeating
+ # the corners
+ forward = np.s_[0:-1] # [0 ... -1)
+ backward = np.s_[-1:0:-1] # [-1 ... 0)
+ return np.concatenate((
+ arr[0, forward],
+ arr[forward, -1],
+ arr[-1, backward],
+ arr[backward, 0],
+ ))
+
+
+def _unfold(arr, axis, size, step):
+ """
+ Append an extra dimension containing sliding windows along *axis*.
+
+ All windows are of size *size* and begin with every *step* elements.
+
+ Parameters
+ ----------
+ arr : ndarray, shape (N_1, ..., N_k)
+ The input array
+ axis : int
+ Axis along which the windows are extracted
+ size : int
+ Size of the windows
+ step : int
+ Stride between first elements of subsequent windows.
+
+ Returns
+ -------
+ ndarray, shape (N_1, ..., 1 + (N_axis-size)/step, ..., N_k, size)
+
+ Examples
+ --------
+ >>> i, j = np.ogrid[:3, :7]
+ >>> a = i*10 + j
+ >>> a
+ array([[ 0, 1, 2, 3, 4, 5, 6],
+ [10, 11, 12, 13, 14, 15, 16],
+ [20, 21, 22, 23, 24, 25, 26]])
+ >>> _unfold(a, axis=1, size=3, step=2)
+ array([[[ 0, 1, 2],
+ [ 2, 3, 4],
+ [ 4, 5, 6]],
+ [[10, 11, 12],
+ [12, 13, 14],
+ [14, 15, 16]],
+ [[20, 21, 22],
+ [22, 23, 24],
+ [24, 25, 26]]])
+ """
+ new_shape = [*arr.shape, size]
+ new_strides = [*arr.strides, arr.strides[axis]]
+ new_shape[axis] = (new_shape[axis] - size) // step + 1
+ new_strides[axis] = new_strides[axis] * step
+ return np.lib.stride_tricks.as_strided(arr,
+ shape=new_shape,
+ strides=new_strides,
+ writeable=False)
+
+
+def _array_patch_perimeters(x, rstride, cstride):
+ """
+ Extract perimeters of patches from *arr*.
+
+ Extracted patches are of size (*rstride* + 1) x (*cstride* + 1) and
+ share perimeters with their neighbors. The ordering of the vertices matches
+ that returned by ``_array_perimeter``.
+
+ Parameters
+ ----------
+ x : ndarray, shape (N, M)
+ Input array
+ rstride : int
+ Vertical (row) stride between corresponding elements of each patch
+ cstride : int
+ Horizontal (column) stride between corresponding elements of each patch
+
+ Returns
+ -------
+ ndarray, shape (N/rstride * M/cstride, 2 * (rstride + cstride))
+ """
+ assert rstride > 0 and cstride > 0
+ assert (x.shape[0] - 1) % rstride == 0
+ assert (x.shape[1] - 1) % cstride == 0
+ # We build up each perimeter from four half-open intervals. Here is an
+ # illustrated explanation for rstride == cstride == 3
+ #
+ # T T T R
+ # L R
+ # L R
+ # L B B B
+ #
+ # where T means that this element will be in the top array, R for right,
+ # B for bottom and L for left. Each of the arrays below has a shape of:
+ #
+ # (number of perimeters that can be extracted vertically,
+ # number of perimeters that can be extracted horizontally,
+ # cstride for top and bottom and rstride for left and right)
+ #
+ # Note that _unfold doesn't incur any memory copies, so the only costly
+ # operation here is the np.concatenate.
+ top = _unfold(x[:-1:rstride, :-1], 1, cstride, cstride)
+ bottom = _unfold(x[rstride::rstride, 1:], 1, cstride, cstride)[..., ::-1]
+ right = _unfold(x[:-1, cstride::cstride], 0, rstride, rstride)
+ left = _unfold(x[1:, :-1:cstride], 0, rstride, rstride)[..., ::-1]
+ return (np.concatenate((top, right, bottom, left), axis=2)
+ .reshape(-1, 2 * (rstride + cstride)))
+
+
+@contextlib.contextmanager
+def _setattr_cm(obj, **kwargs):
+ """
+ Temporarily set some attributes; restore original state at context exit.
+ """
+ sentinel = object()
+ origs = {}
+ for attr in kwargs:
+ orig = getattr(obj, attr, sentinel)
+ if attr in obj.__dict__ or orig is sentinel:
+ # if we are pulling from the instance dict or the object
+ # does not have this attribute we can trust the above
+ origs[attr] = orig
+ else:
+ # if the attribute is not in the instance dict it must be
+ # from the class level
+ cls_orig = getattr(type(obj), attr)
+ # if we are dealing with a property (but not a general descriptor)
+ # we want to set the original value back.
+ if isinstance(cls_orig, property):
+ origs[attr] = orig
+ # otherwise this is _something_ we are going to shadow at
+ # the instance dict level from higher up in the MRO. We
+ # are going to assume we can delattr(obj, attr) to clean
+ # up after ourselves. It is possible that this code will
+ # fail if used with a non-property custom descriptor which
+ # implements __set__ (and __delete__ does not act like a
+ # stack). However, this is an internal tool and we do not
+ # currently have any custom descriptors.
+ else:
+ origs[attr] = sentinel
+
+ try:
+ for attr, val in kwargs.items():
+ setattr(obj, attr, val)
+ yield
+ finally:
+ for attr, orig in origs.items():
+ if orig is sentinel:
+ delattr(obj, attr)
+ else:
+ setattr(obj, attr, orig)
+
+
+class _OrderedSet(collections.abc.MutableSet):
+ def __init__(self):
+ self._od = collections.OrderedDict()
+
+ def __contains__(self, key):
+ return key in self._od
+
+ def __iter__(self):
+ return iter(self._od)
+
+ def __len__(self):
+ return len(self._od)
+
+ def add(self, key):
+ self._od.pop(key, None)
+ self._od[key] = None
+
+ def discard(self, key):
+ self._od.pop(key, None)
+
+
+# Agg's buffers are unmultiplied RGBA8888, which neither PyQt<=5.1 nor cairo
+# support; however, both do support premultiplied ARGB32.
+
+
+def _premultiplied_argb32_to_unmultiplied_rgba8888(buf):
+ """
+ Convert a premultiplied ARGB32 buffer to an unmultiplied RGBA8888 buffer.
+ """
+ rgba = np.take( # .take() ensures C-contiguity of the result.
+ buf,
+ [2, 1, 0, 3] if sys.byteorder == "little" else [1, 2, 3, 0], axis=2)
+ rgb = rgba[..., :-1]
+ alpha = rgba[..., -1]
+ # Un-premultiply alpha. The formula is the same as in cairo-png.c.
+ mask = alpha != 0
+ for channel in np.rollaxis(rgb, -1):
+ channel[mask] = (
+ (channel[mask].astype(int) * 255 + alpha[mask] // 2)
+ // alpha[mask])
+ return rgba
+
+
+def _unmultiplied_rgba8888_to_premultiplied_argb32(rgba8888):
+ """
+ Convert an unmultiplied RGBA8888 buffer to a premultiplied ARGB32 buffer.
+ """
+ if sys.byteorder == "little":
+ argb32 = np.take(rgba8888, [2, 1, 0, 3], axis=2)
+ rgb24 = argb32[..., :-1]
+ alpha8 = argb32[..., -1:]
+ else:
+ argb32 = np.take(rgba8888, [3, 0, 1, 2], axis=2)
+ alpha8 = argb32[..., :1]
+ rgb24 = argb32[..., 1:]
+ # Only bother premultiplying when the alpha channel is not fully opaque,
+ # as the cost is not negligible. The unsafe cast is needed to do the
+ # multiplication in-place in an integer buffer.
+ if alpha8.min() != 0xff:
+ np.multiply(rgb24, alpha8 / 0xff, out=rgb24, casting="unsafe")
+ return argb32
+
+
+def _get_nonzero_slices(buf):
+ """
+ Return the bounds of the nonzero region of a 2D array as a pair of slices.
+
+ ``buf[_get_nonzero_slices(buf)]`` is the smallest sub-rectangle in *buf*
+ that encloses all non-zero entries in *buf*. If *buf* is fully zero, then
+ ``(slice(0, 0), slice(0, 0))`` is returned.
+ """
+ x_nz, = buf.any(axis=0).nonzero()
+ y_nz, = buf.any(axis=1).nonzero()
+ if len(x_nz) and len(y_nz):
+ l, r = x_nz[[0, -1]]
+ b, t = y_nz[[0, -1]]
+ return slice(b, t + 1), slice(l, r + 1)
+ else:
+ return slice(0, 0), slice(0, 0)
+
+
+def _pformat_subprocess(command):
+ """Pretty-format a subprocess command for printing/logging purposes."""
+ return (command if isinstance(command, str)
+ else " ".join(shlex.quote(os.fspath(arg)) for arg in command))
+
+
+def _check_and_log_subprocess(command, logger, **kwargs):
+ """
+ Run *command*, returning its stdout output if it succeeds.
+
+ If it fails (exits with nonzero return code), raise an exception whose text
+ includes the failed command and captured stdout and stderr output.
+
+ Regardless of the return code, the command is logged at DEBUG level on
+ *logger*. In case of success, the output is likewise logged.
+ """
+ logger.debug('%s', _pformat_subprocess(command))
+ proc = subprocess.run(command, capture_output=True, **kwargs)
+ if proc.returncode:
+ stdout = proc.stdout
+ if isinstance(stdout, bytes):
+ stdout = stdout.decode()
+ stderr = proc.stderr
+ if isinstance(stderr, bytes):
+ stderr = stderr.decode()
+ raise RuntimeError(
+ f"The command\n"
+ f" {_pformat_subprocess(command)}\n"
+ f"failed and generated the following output:\n"
+ f"{stdout}\n"
+ f"and the following error:\n"
+ f"{stderr}")
+ if proc.stdout:
+ logger.debug("stdout:\n%s", proc.stdout)
+ if proc.stderr:
+ logger.debug("stderr:\n%s", proc.stderr)
+ return proc.stdout
+
+
+def _setup_new_guiapp():
+ """
+ Perform OS-dependent setup when Matplotlib creates a new GUI application.
+ """
+ # Windows: If not explicit app user model id has been set yet (so we're not
+ # already embedded), then set it to "matplotlib", so that taskbar icons are
+ # correct.
+ try:
+ _c_internal_utils.Win32_GetCurrentProcessExplicitAppUserModelID()
+ except OSError:
+ _c_internal_utils.Win32_SetCurrentProcessExplicitAppUserModelID(
+ "matplotlib")
+
+
+def _format_approx(number, precision):
+ """
+ Format the number with at most the number of decimals given as precision.
+ Remove trailing zeros and possibly the decimal point.
+ """
+ return f'{number:.{precision}f}'.rstrip('0').rstrip('.') or '0'
+
+
+def _g_sig_digits(value, delta):
+ """
+ Return the number of significant digits to %g-format *value*, assuming that
+ it is known with an error of *delta*.
+ """
+ # For inf or nan, the precision doesn't matter.
+ if not math.isfinite(value):
+ return 0
+ if delta == 0:
+ if value == 0:
+ # if both value and delta are 0, np.spacing below returns 5e-324
+ # which results in rather silly results
+ return 3
+ # delta = 0 may occur when trying to format values over a tiny range;
+ # in that case, replace it by the distance to the closest float.
+ delta = abs(np.spacing(value))
+ # If e.g. value = 45.67 and delta = 0.02, then we want to round to 2 digits
+ # after the decimal point (floor(log10(0.02)) = -2); 45.67 contributes 2
+ # digits before the decimal point (floor(log10(45.67)) + 1 = 2): the total
+ # is 4 significant digits. A value of 0 contributes 1 "digit" before the
+ # decimal point.
+ return max(
+ 0,
+ (math.floor(math.log10(abs(value))) + 1 if value else 1)
+ - math.floor(math.log10(delta)))
+
+
+def _unikey_or_keysym_to_mplkey(unikey, keysym):
+ """
+ Convert a Unicode key or X keysym to a Matplotlib key name.
+
+ The Unicode key is checked first; this avoids having to list most printable
+ keysyms such as ``EuroSign``.
+ """
+ # For non-printable characters, gtk3 passes "\0" whereas tk passes an "".
+ if unikey and unikey.isprintable():
+ return unikey
+ key = keysym.lower()
+ if key.startswith("kp_"): # keypad_x (including kp_enter).
+ key = key[3:]
+ if key.startswith("page_"): # page_{up,down}
+ key = key.replace("page_", "page")
+ if key.endswith(("_l", "_r")): # alt_l, ctrl_l, shift_l.
+ key = key[:-2]
+ if sys.platform == "darwin" and key == "meta":
+ # meta should be reported as command on mac
+ key = "cmd"
+ key = {
+ "return": "enter",
+ "prior": "pageup", # Used by tk.
+ "next": "pagedown", # Used by tk.
+ }.get(key, key)
+ return key
+
+
+@functools.cache
+def _make_class_factory(mixin_class, fmt, attr_name=None):
+ """
+ Return a function that creates picklable classes inheriting from a mixin.
+
+ After ::
+
+ factory = _make_class_factory(FooMixin, fmt, attr_name)
+ FooAxes = factory(Axes)
+
+ ``Foo`` is a class that inherits from ``FooMixin`` and ``Axes`` and **is
+ picklable** (picklability is what differentiates this from a plain call to
+ `type`). Its ``__name__`` is set to ``fmt.format(Axes.__name__)`` and the
+ base class is stored in the ``attr_name`` attribute, if not None.
+
+ Moreover, the return value of ``factory`` is memoized: calls with the same
+ ``Axes`` class always return the same subclass.
+ """
+
+ @functools.cache
+ def class_factory(axes_class):
+ # if we have already wrapped this class, declare victory!
+ if issubclass(axes_class, mixin_class):
+ return axes_class
+
+ # The parameter is named "axes_class" for backcompat but is really just
+ # a base class; no axes semantics are used.
+ base_class = axes_class
+
+ class subcls(mixin_class, base_class):
+ # Better approximation than __module__ = "matplotlib.cbook".
+ __module__ = mixin_class.__module__
+
+ def __reduce__(self):
+ return (_picklable_class_constructor,
+ (mixin_class, fmt, attr_name, base_class),
+ self.__getstate__())
+
+ subcls.__name__ = subcls.__qualname__ = fmt.format(base_class.__name__)
+ if attr_name is not None:
+ setattr(subcls, attr_name, base_class)
+ return subcls
+
+ class_factory.__module__ = mixin_class.__module__
+ return class_factory
+
+
+def _picklable_class_constructor(mixin_class, fmt, attr_name, base_class):
+ """Internal helper for _make_class_factory."""
+ factory = _make_class_factory(mixin_class, fmt, attr_name)
+ cls = factory(base_class)
+ return cls.__new__(cls)
+
+
+def _is_torch_array(x):
+ """Return whether *x* is a PyTorch Tensor."""
+ try:
+ # We're intentionally not attempting to import torch. If somebody
+ # has created a torch array, torch should already be in sys.modules.
+ tp = sys.modules.get("torch").Tensor
+ except AttributeError:
+ return False # Module not imported or a nonstandard module with no Tensor attr.
+ return (isinstance(tp, type) # Just in case it's a very nonstandard module.
+ and isinstance(x, tp))
+
+
+def _is_jax_array(x):
+ """Return whether *x* is a JAX Array."""
+ try:
+ # We're intentionally not attempting to import jax. If somebody
+ # has created a jax array, jax should already be in sys.modules.
+ tp = sys.modules.get("jax").Array
+ except AttributeError:
+ return False # Module not imported or a nonstandard module with no Array attr.
+ return (isinstance(tp, type) # Just in case it's a very nonstandard module.
+ and isinstance(x, tp))
+
+
+def _is_pandas_dataframe(x):
+ """Check if *x* is a Pandas DataFrame."""
+ try:
+ # We're intentionally not attempting to import Pandas. If somebody
+ # has created a Pandas DataFrame, Pandas should already be in sys.modules.
+ tp = sys.modules.get("pandas").DataFrame
+ except AttributeError:
+ return False # Module not imported or a nonstandard module with no Array attr.
+ return (isinstance(tp, type) # Just in case it's a very nonstandard module.
+ and isinstance(x, tp))
+
+
+def _is_tensorflow_array(x):
+ """Return whether *x* is a TensorFlow Tensor or Variable."""
+ try:
+ # We're intentionally not attempting to import TensorFlow. If somebody
+ # has created a TensorFlow array, TensorFlow should already be in
+ # sys.modules we use `is_tensor` to not depend on the class structure
+ # of TensorFlow arrays, as `tf.Variables` are not instances of
+ # `tf.Tensor` (they both convert the same way).
+ is_tensor = sys.modules.get("tensorflow").is_tensor
+ except AttributeError:
+ return False
+ try:
+ return is_tensor(x)
+ except Exception:
+ return False # Just in case it's a very nonstandard module.
+
+
+def _unpack_to_numpy(x):
+ """Internal helper to extract data from e.g. pandas and xarray objects."""
+ if isinstance(x, np.ndarray):
+ # If numpy, return directly
+ return x
+ if hasattr(x, 'to_numpy'):
+ # Assume that any to_numpy() method actually returns a numpy array
+ return x.to_numpy()
+ if hasattr(x, 'values'):
+ xtmp = x.values
+ # For example a dict has a 'values' attribute, but it is not a property
+ # so in this case we do not want to return a function
+ if isinstance(xtmp, np.ndarray):
+ return xtmp
+ if _is_torch_array(x) or _is_jax_array(x) or _is_tensorflow_array(x):
+ # using np.asarray() instead of explicitly __array__(), as the latter is
+ # only _one_ of many methods, and it's the last resort, see also
+ # https://numpy.org/devdocs/user/basics.interoperability.html#using-arbitrary-objects-in-numpy
+ # therefore, let arrays do better if they can
+ xtmp = np.asarray(x)
+
+ # In case np.asarray method does not return a numpy array in future
+ if isinstance(xtmp, np.ndarray):
+ return xtmp
+ return x
+
+
+def _auto_format_str(fmt, value):
+ """
+ Apply *value* to the format string *fmt*.
+
+ This works both with unnamed %-style formatting and
+ unnamed {}-style formatting. %-style formatting has priority.
+ If *fmt* is %-style formattable that will be used. Otherwise,
+ {}-formatting is applied. Strings without formatting placeholders
+ are passed through as is.
+
+ Examples
+ --------
+ >>> _auto_format_str('%.2f m', 0.2)
+ '0.20 m'
+ >>> _auto_format_str('{} m', 0.2)
+ '0.2 m'
+ >>> _auto_format_str('const', 0.2)
+ 'const'
+ >>> _auto_format_str('%d or {}', 0.2)
+ '0 or {}'
+ """
+ try:
+ return fmt % (value,)
+ except (TypeError, ValueError):
+ return fmt.format(value)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/cbook.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/cbook.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..cc6b4e8f4e1963922a75a140ff127d9bb5ead58c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/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/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/cm.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/cm.py
new file mode 100644
index 0000000000000000000000000000000000000000..0c11527bc2b925d57cdd7198a10c13118cfe9d16
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/cm.py
@@ -0,0 +1,310 @@
+"""
+Builtin colormaps, colormap handling utilities, and the `ScalarMappable` mixin.
+
+.. seealso::
+
+ :doc:`/gallery/color/colormap_reference` for a list of builtin colormaps.
+
+ :ref:`colormap-manipulation` for examples of how to make
+ colormaps.
+
+ :ref:`colormaps` an in-depth discussion of choosing
+ colormaps.
+
+ :ref:`colormapnorms` for more details about data normalization.
+"""
+
+from collections.abc import Mapping
+
+import matplotlib as mpl
+from matplotlib import _api, colors
+# TODO make this warn on access
+from matplotlib.colorizer import _ScalarMappable as ScalarMappable # noqa
+from matplotlib._cm import datad
+from matplotlib._cm_listed import cmaps as cmaps_listed
+from matplotlib._cm_multivar import cmap_families as multivar_cmaps
+from matplotlib._cm_bivar import cmaps as bivar_cmaps
+
+
+_LUTSIZE = mpl.rcParams['image.lut']
+
+
+def _gen_cmap_registry():
+ """
+ Generate a dict mapping standard colormap names to standard colormaps, as
+ well as the reversed colormaps.
+ """
+ cmap_d = {**cmaps_listed}
+ for name, spec in datad.items():
+ cmap_d[name] = ( # Precache the cmaps at a fixed lutsize..
+ colors.LinearSegmentedColormap(name, spec, _LUTSIZE)
+ if 'red' in spec else
+ colors.ListedColormap(spec['listed'], name)
+ if 'listed' in spec else
+ colors.LinearSegmentedColormap.from_list(name, spec, _LUTSIZE))
+
+ # Register colormap aliases for gray and grey.
+ aliases = {
+ # alias -> original name
+ 'grey': 'gray',
+ 'gist_grey': 'gist_gray',
+ 'gist_yerg': 'gist_yarg',
+ 'Grays': 'Greys',
+ }
+ for alias, original_name in aliases.items():
+ cmap = cmap_d[original_name].copy()
+ cmap.name = alias
+ cmap_d[alias] = cmap
+
+ # Generate reversed cmaps.
+ for cmap in list(cmap_d.values()):
+ rmap = cmap.reversed()
+ cmap_d[rmap.name] = rmap
+ return cmap_d
+
+
+class ColormapRegistry(Mapping):
+ r"""
+ Container for colormaps that are known to Matplotlib by name.
+
+ The universal registry instance is `matplotlib.colormaps`. There should be
+ no need for users to instantiate `.ColormapRegistry` themselves.
+
+ Read access uses a dict-like interface mapping names to `.Colormap`\s::
+
+ import matplotlib as mpl
+ cmap = mpl.colormaps['viridis']
+
+ Returned `.Colormap`\s are copies, so that their modification does not
+ change the global definition of the colormap.
+
+ Additional colormaps can be added via `.ColormapRegistry.register`::
+
+ mpl.colormaps.register(my_colormap)
+
+ To get a list of all registered colormaps, you can do::
+
+ from matplotlib import colormaps
+ list(colormaps)
+ """
+ def __init__(self, cmaps):
+ self._cmaps = cmaps
+ self._builtin_cmaps = tuple(cmaps)
+
+ def __getitem__(self, item):
+ try:
+ return self._cmaps[item].copy()
+ except KeyError:
+ raise KeyError(f"{item!r} is not a known colormap name") from None
+
+ def __iter__(self):
+ return iter(self._cmaps)
+
+ def __len__(self):
+ return len(self._cmaps)
+
+ def __str__(self):
+ return ('ColormapRegistry; available colormaps:\n' +
+ ', '.join(f"'{name}'" for name in self))
+
+ def __call__(self):
+ """
+ Return a list of the registered colormap names.
+
+ This exists only for backward-compatibility in `.pyplot` which had a
+ ``plt.colormaps()`` method. The recommended way to get this list is
+ now ``list(colormaps)``.
+ """
+ return list(self)
+
+ def register(self, cmap, *, name=None, force=False):
+ """
+ Register a new colormap.
+
+ The colormap name can then be used as a string argument to any ``cmap``
+ parameter in Matplotlib. It is also available in ``pyplot.get_cmap``.
+
+ The colormap registry stores a copy of the given colormap, so that
+ future changes to the original colormap instance do not affect the
+ registered colormap. Think of this as the registry taking a snapshot
+ of the colormap at registration.
+
+ Parameters
+ ----------
+ cmap : matplotlib.colors.Colormap
+ The colormap to register.
+
+ name : str, optional
+ The name for the colormap. If not given, ``cmap.name`` is used.
+
+ force : bool, default: False
+ If False, a ValueError is raised if trying to overwrite an already
+ registered name. True supports overwriting registered colormaps
+ other than the builtin colormaps.
+ """
+ _api.check_isinstance(colors.Colormap, cmap=cmap)
+
+ name = name or cmap.name
+ if name in self:
+ if not force:
+ # don't allow registering an already existing cmap
+ # unless explicitly asked to
+ raise ValueError(
+ f'A colormap named "{name}" is already registered.')
+ elif name in self._builtin_cmaps:
+ # We don't allow overriding a builtin.
+ raise ValueError("Re-registering the builtin cmap "
+ f"{name!r} is not allowed.")
+
+ # Warn that we are updating an already existing colormap
+ _api.warn_external(f"Overwriting the cmap {name!r} "
+ "that was already in the registry.")
+
+ self._cmaps[name] = cmap.copy()
+ # Someone may set the extremes of a builtin colormap and want to register it
+ # with a different name for future lookups. The object would still have the
+ # builtin name, so we should update it to the registered name
+ if self._cmaps[name].name != name:
+ self._cmaps[name].name = name
+
+ def unregister(self, name):
+ """
+ Remove a colormap from the registry.
+
+ You cannot remove built-in colormaps.
+
+ If the named colormap is not registered, returns with no error, raises
+ if you try to de-register a default colormap.
+
+ .. warning::
+
+ Colormap names are currently a shared namespace that may be used
+ by multiple packages. Use `unregister` only if you know you
+ have registered that name before. In particular, do not
+ unregister just in case to clean the name before registering a
+ new colormap.
+
+ Parameters
+ ----------
+ name : str
+ The name of the colormap to be removed.
+
+ Raises
+ ------
+ ValueError
+ If you try to remove a default built-in colormap.
+ """
+ if name in self._builtin_cmaps:
+ raise ValueError(f"cannot unregister {name!r} which is a builtin "
+ "colormap.")
+ self._cmaps.pop(name, None)
+
+ def get_cmap(self, cmap):
+ """
+ Return a color map specified through *cmap*.
+
+ Parameters
+ ----------
+ cmap : str or `~matplotlib.colors.Colormap` or None
+
+ - if a `.Colormap`, return it
+ - if a string, look it up in ``mpl.colormaps``
+ - if None, return the Colormap defined in :rc:`image.cmap`
+
+ Returns
+ -------
+ Colormap
+ """
+ # get the default color map
+ if cmap is None:
+ return self[mpl.rcParams["image.cmap"]]
+
+ # if the user passed in a Colormap, simply return it
+ if isinstance(cmap, colors.Colormap):
+ return cmap
+ if isinstance(cmap, str):
+ _api.check_in_list(sorted(_colormaps), cmap=cmap)
+ # otherwise, it must be a string so look it up
+ return self[cmap]
+ raise TypeError(
+ 'get_cmap expects None or an instance of a str or Colormap . ' +
+ f'you passed {cmap!r} of type {type(cmap)}'
+ )
+
+
+# public access to the colormaps should be via `matplotlib.colormaps`. For now,
+# we still create the registry here, but that should stay an implementation
+# detail.
+_colormaps = ColormapRegistry(_gen_cmap_registry())
+globals().update(_colormaps)
+
+_multivar_colormaps = ColormapRegistry(multivar_cmaps)
+
+_bivar_colormaps = ColormapRegistry(bivar_cmaps)
+
+
+# This is an exact copy of pyplot.get_cmap(). It was removed in 3.9, but apparently
+# caused more user trouble than expected. Re-added for 3.9.1 and extended the
+# deprecation period for two additional minor releases.
+@_api.deprecated(
+ '3.7',
+ removal='3.11',
+ alternative="``matplotlib.colormaps[name]`` or ``matplotlib.colormaps.get_cmap()``"
+ " or ``pyplot.get_cmap()``"
+ )
+def get_cmap(name=None, lut=None):
+ """
+ Get a colormap instance, defaulting to rc values if *name* is None.
+
+ Parameters
+ ----------
+ name : `~matplotlib.colors.Colormap` or str or None, default: None
+ If a `.Colormap` instance, it will be returned. Otherwise, the name of
+ a colormap known to Matplotlib, which will be resampled by *lut*. The
+ default, None, means :rc:`image.cmap`.
+ lut : int or None, default: None
+ If *name* is not already a Colormap instance and *lut* is not None, the
+ colormap will be resampled to have *lut* entries in the lookup table.
+
+ Returns
+ -------
+ Colormap
+ """
+ if name is None:
+ name = mpl.rcParams['image.cmap']
+ if isinstance(name, colors.Colormap):
+ return name
+ _api.check_in_list(sorted(_colormaps), name=name)
+ if lut is None:
+ return _colormaps[name]
+ else:
+ return _colormaps[name].resampled(lut)
+
+
+def _ensure_cmap(cmap):
+ """
+ Ensure that we have a `.Colormap` object.
+
+ For internal use to preserve type stability of errors.
+
+ Parameters
+ ----------
+ cmap : None, str, Colormap
+
+ - if a `Colormap`, return it
+ - if a string, look it up in mpl.colormaps
+ - if None, look up the default color map in mpl.colormaps
+
+ Returns
+ -------
+ Colormap
+
+ """
+ if isinstance(cmap, colors.Colormap):
+ return cmap
+ cmap_name = cmap if cmap is not None else mpl.rcParams["image.cmap"]
+ # use check_in_list to ensure type stability of the exception raised by
+ # the internal usage of this (ValueError vs KeyError)
+ if cmap_name not in _colormaps:
+ _api.check_in_list(sorted(_colormaps), cmap=cmap_name)
+ return mpl.colormaps[cmap_name]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/cm.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/cm.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..c3c62095684aaa7b7a59490412889096b3cded61
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/cm.pyi
@@ -0,0 +1,24 @@
+from collections.abc import Iterator, Mapping
+from matplotlib import colors
+from matplotlib.colorizer import _ScalarMappable
+
+
+class ColormapRegistry(Mapping[str, colors.Colormap]):
+ def __init__(self, cmaps: Mapping[str, colors.Colormap]) -> None: ...
+ def __getitem__(self, item: str) -> colors.Colormap: ...
+ def __iter__(self) -> Iterator[str]: ...
+ def __len__(self) -> int: ...
+ def __call__(self) -> list[str]: ...
+ def register(
+ self, cmap: colors.Colormap, *, name: str | None = ..., force: bool = ...
+ ) -> None: ...
+ def unregister(self, name: str) -> None: ...
+ def get_cmap(self, cmap: str | colors.Colormap) -> colors.Colormap: ...
+
+_colormaps: ColormapRegistry = ...
+_multivar_colormaps: ColormapRegistry = ...
+_bivar_colormaps: ColormapRegistry = ...
+
+def get_cmap(name: str | colors.Colormap | None = ..., lut: int | None = ...) -> colors.Colormap: ...
+
+ScalarMappable = _ScalarMappable
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/collections.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/collections.py
new file mode 100644
index 0000000000000000000000000000000000000000..9bc25913ee0e18c77be987d5c6b2afc602155557
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/collections.py
@@ -0,0 +1,2573 @@
+"""
+Classes for the efficient drawing of large collections of objects that
+share most properties, e.g., a large number of line segments or
+polygons.
+
+The classes are not meant to be as flexible as their single element
+counterparts (e.g., you may not be able to select all line styles) but
+they are meant to be fast for common use cases (e.g., a large set of solid
+line segments).
+"""
+
+import itertools
+import functools
+import math
+from numbers import Number, Real
+import warnings
+
+import numpy as np
+
+import matplotlib as mpl
+from . import (_api, _path, artist, cbook, colorizer as mcolorizer, colors as mcolors,
+ _docstring, hatch as mhatch, lines as mlines, path as mpath, transforms)
+from ._enums import JoinStyle, CapStyle
+
+
+# "color" is excluded; it is a compound setter, and its docstring differs
+# in LineCollection.
+@_api.define_aliases({
+ "antialiased": ["antialiaseds", "aa"],
+ "edgecolor": ["edgecolors", "ec"],
+ "facecolor": ["facecolors", "fc"],
+ "linestyle": ["linestyles", "dashes", "ls"],
+ "linewidth": ["linewidths", "lw"],
+ "offset_transform": ["transOffset"],
+})
+class Collection(mcolorizer.ColorizingArtist):
+ r"""
+ Base class for Collections. Must be subclassed to be usable.
+
+ A Collection represents a sequence of `.Patch`\es that can be drawn
+ more efficiently together than individually. For example, when a single
+ path is being drawn repeatedly at different offsets, the renderer can
+ typically execute a ``draw_marker()`` call much more efficiently than a
+ series of repeated calls to ``draw_path()`` with the offsets put in
+ one-by-one.
+
+ Most properties of a collection can be configured per-element. Therefore,
+ Collections have "plural" versions of many of the properties of a `.Patch`
+ (e.g. `.Collection.get_paths` instead of `.Patch.get_path`). Exceptions are
+ the *zorder*, *hatch*, *pickradius*, *capstyle* and *joinstyle* properties,
+ which can only be set globally for the whole collection.
+
+ Besides these exceptions, all properties can be specified as single values
+ (applying to all elements) or sequences of values. The property of the
+ ``i``\th element of the collection is::
+
+ prop[i % len(prop)]
+
+ Each Collection can optionally be used as its own `.ScalarMappable` by
+ passing the *norm* and *cmap* parameters to its constructor. If the
+ Collection's `.ScalarMappable` matrix ``_A`` has been set (via a call
+ to `.Collection.set_array`), then at draw time this internal scalar
+ mappable will be used to set the ``facecolors`` and ``edgecolors``,
+ ignoring those that were manually passed in.
+ """
+ #: Either a list of 3x3 arrays or an Nx3x3 array (representing N
+ #: transforms), suitable for the `all_transforms` argument to
+ #: `~matplotlib.backend_bases.RendererBase.draw_path_collection`;
+ #: each 3x3 array is used to initialize an
+ #: `~matplotlib.transforms.Affine2D` object.
+ #: Each kind of collection defines this based on its arguments.
+ _transforms = np.empty((0, 3, 3))
+
+ # Whether to draw an edge by default. Set on a
+ # subclass-by-subclass basis.
+ _edge_default = False
+
+ @_docstring.interpd
+ def __init__(self, *,
+ edgecolors=None,
+ facecolors=None,
+ linewidths=None,
+ linestyles='solid',
+ capstyle=None,
+ joinstyle=None,
+ antialiaseds=None,
+ offsets=None,
+ offset_transform=None,
+ norm=None, # optional for ScalarMappable
+ cmap=None, # ditto
+ colorizer=None,
+ pickradius=5.0,
+ hatch=None,
+ urls=None,
+ zorder=1,
+ **kwargs
+ ):
+ """
+ Parameters
+ ----------
+ edgecolors : :mpltype:`color` or list of colors, default: :rc:`patch.edgecolor`
+ Edge color for each patch making up the collection. The special
+ value 'face' can be passed to make the edgecolor match the
+ facecolor.
+ facecolors : :mpltype:`color` or list of colors, default: :rc:`patch.facecolor`
+ Face color for each patch making up the collection.
+ linewidths : float or list of floats, default: :rc:`patch.linewidth`
+ Line width for each patch making up the collection.
+ linestyles : str or tuple or list thereof, default: 'solid'
+ Valid strings are ['solid', 'dashed', 'dashdot', 'dotted', '-',
+ '--', '-.', ':']. Dash tuples should be of the form::
+
+ (offset, onoffseq),
+
+ where *onoffseq* is an even length tuple of on and off ink lengths
+ in points. For examples, see
+ :doc:`/gallery/lines_bars_and_markers/linestyles`.
+ capstyle : `.CapStyle`-like, default: 'butt'
+ Style to use for capping lines for all paths in the collection.
+ Allowed values are %(CapStyle)s.
+ joinstyle : `.JoinStyle`-like, default: 'round'
+ Style to use for joining lines for all paths in the collection.
+ Allowed values are %(JoinStyle)s.
+ antialiaseds : bool or list of bool, default: :rc:`patch.antialiased`
+ Whether each patch in the collection should be drawn with
+ antialiasing.
+ offsets : (float, float) or list thereof, default: (0, 0)
+ A vector by which to translate each patch after rendering (default
+ is no translation). The translation is performed in screen (pixel)
+ coordinates (i.e. after the Artist's transform is applied).
+ offset_transform : `~.Transform`, default: `.IdentityTransform`
+ A single transform which will be applied to each *offsets* vector
+ before it is used.
+ cmap, norm
+ Data normalization and colormapping parameters. See
+ `.ScalarMappable` for a detailed description.
+ hatch : str, optional
+ Hatching pattern to use in filled paths, if any. Valid strings are
+ ['/', '\\', '|', '-', '+', 'x', 'o', 'O', '.', '*']. See
+ :doc:`/gallery/shapes_and_collections/hatch_style_reference` for
+ the meaning of each hatch type.
+ pickradius : float, default: 5.0
+ If ``pickradius <= 0``, then `.Collection.contains` will return
+ ``True`` whenever the test point is inside of one of the polygons
+ formed by the control points of a Path in the Collection. On the
+ other hand, if it is greater than 0, then we instead check if the
+ test point is contained in a stroke of width ``2*pickradius``
+ following any of the Paths in the Collection.
+ urls : list of str, default: None
+ A URL for each patch to link to once drawn. Currently only works
+ for the SVG backend. See :doc:`/gallery/misc/hyperlinks_sgskip` for
+ examples.
+ zorder : float, default: 1
+ The drawing order, shared by all Patches in the Collection. See
+ :doc:`/gallery/misc/zorder_demo` for all defaults and examples.
+ **kwargs
+ Remaining keyword arguments will be used to set properties as
+ ``Collection.set_{key}(val)`` for each key-value pair in *kwargs*.
+ """
+
+ super().__init__(self._get_colorizer(cmap, norm, colorizer))
+ # list of un-scaled dash patterns
+ # this is needed scaling the dash pattern by linewidth
+ self._us_linestyles = [(0, None)]
+ # list of dash patterns
+ self._linestyles = [(0, None)]
+ # list of unbroadcast/scaled linewidths
+ self._us_lw = [0]
+ self._linewidths = [0]
+
+ self._gapcolor = None # Currently only used by LineCollection.
+
+ # Flags set by _set_mappable_flags: are colors from mapping an array?
+ self._face_is_mapped = None
+ self._edge_is_mapped = None
+ self._mapped_colors = None # calculated in update_scalarmappable
+ self._hatch_color = mcolors.to_rgba(mpl.rcParams['hatch.color'])
+ self._hatch_linewidth = mpl.rcParams['hatch.linewidth']
+ self.set_facecolor(facecolors)
+ self.set_edgecolor(edgecolors)
+ self.set_linewidth(linewidths)
+ self.set_linestyle(linestyles)
+ self.set_antialiased(antialiaseds)
+ self.set_pickradius(pickradius)
+ self.set_urls(urls)
+ self.set_hatch(hatch)
+ self.set_zorder(zorder)
+
+ if capstyle:
+ self.set_capstyle(capstyle)
+ else:
+ self._capstyle = None
+
+ if joinstyle:
+ self.set_joinstyle(joinstyle)
+ else:
+ self._joinstyle = None
+
+ if offsets is not None:
+ offsets = np.asanyarray(offsets, float)
+ # Broadcast (2,) -> (1, 2) but nothing else.
+ if offsets.shape == (2,):
+ offsets = offsets[None, :]
+
+ self._offsets = offsets
+ self._offset_transform = offset_transform
+
+ self._path_effects = None
+ self._internal_update(kwargs)
+ self._paths = None
+
+ def get_paths(self):
+ return self._paths
+
+ def set_paths(self, paths):
+ self._paths = paths
+ self.stale = True
+
+ def get_transforms(self):
+ return self._transforms
+
+ def get_offset_transform(self):
+ """Return the `.Transform` instance used by this artist offset."""
+ if self._offset_transform is None:
+ self._offset_transform = transforms.IdentityTransform()
+ elif (not isinstance(self._offset_transform, transforms.Transform)
+ and hasattr(self._offset_transform, '_as_mpl_transform')):
+ self._offset_transform = \
+ self._offset_transform._as_mpl_transform(self.axes)
+ return self._offset_transform
+
+ def set_offset_transform(self, offset_transform):
+ """
+ Set the artist offset transform.
+
+ Parameters
+ ----------
+ offset_transform : `.Transform`
+ """
+ self._offset_transform = offset_transform
+
+ def get_datalim(self, transData):
+ # Calculate the data limits and return them as a `.Bbox`.
+ #
+ # This operation depends on the transforms for the data in the
+ # collection and whether the collection has offsets:
+ #
+ # 1. offsets = None, transform child of transData: use the paths for
+ # the automatic limits (i.e. for LineCollection in streamline).
+ # 2. offsets != None: offset_transform is child of transData:
+ #
+ # a. transform is child of transData: use the path + offset for
+ # limits (i.e for bar).
+ # b. transform is not a child of transData: just use the offsets
+ # for the limits (i.e. for scatter)
+ #
+ # 3. otherwise return a null Bbox.
+
+ transform = self.get_transform()
+ offset_trf = self.get_offset_transform()
+ if not (isinstance(offset_trf, transforms.IdentityTransform)
+ or offset_trf.contains_branch(transData)):
+ # if the offsets are in some coords other than data,
+ # then don't use them for autoscaling.
+ return transforms.Bbox.null()
+
+ paths = self.get_paths()
+ if not len(paths):
+ # No paths to transform
+ return transforms.Bbox.null()
+
+ if not transform.is_affine:
+ paths = [transform.transform_path_non_affine(p) for p in paths]
+ # Don't convert transform to transform.get_affine() here because
+ # we may have transform.contains_branch(transData) but not
+ # transforms.get_affine().contains_branch(transData). But later,
+ # be careful to only apply the affine part that remains.
+
+ offsets = self.get_offsets()
+
+ if any(transform.contains_branch_seperately(transData)):
+ # collections that are just in data units (like quiver)
+ # can properly have the axes limits set by their shape +
+ # offset. LineCollections that have no offsets can
+ # also use this algorithm (like streamplot).
+ if isinstance(offsets, np.ma.MaskedArray):
+ offsets = offsets.filled(np.nan)
+ # get_path_collection_extents handles nan but not masked arrays
+ return mpath.get_path_collection_extents(
+ transform.get_affine() - transData, paths,
+ self.get_transforms(),
+ offset_trf.transform_non_affine(offsets),
+ offset_trf.get_affine().frozen())
+
+ # NOTE: None is the default case where no offsets were passed in
+ if self._offsets is not None:
+ # this is for collections that have their paths (shapes)
+ # in physical, axes-relative, or figure-relative units
+ # (i.e. like scatter). We can't uniquely set limits based on
+ # those shapes, so we just set the limits based on their
+ # location.
+ offsets = (offset_trf - transData).transform(offsets)
+ # note A-B means A B^{-1}
+ offsets = np.ma.masked_invalid(offsets)
+ if not offsets.mask.all():
+ bbox = transforms.Bbox.null()
+ bbox.update_from_data_xy(offsets)
+ return bbox
+ return transforms.Bbox.null()
+
+ def get_window_extent(self, renderer=None):
+ # TODO: check to ensure that this does not fail for
+ # cases other than scatter plot legend
+ return self.get_datalim(transforms.IdentityTransform())
+
+ def _prepare_points(self):
+ # Helper for drawing and hit testing.
+
+ transform = self.get_transform()
+ offset_trf = self.get_offset_transform()
+ offsets = self.get_offsets()
+ paths = self.get_paths()
+
+ if self.have_units():
+ paths = []
+ for path in self.get_paths():
+ vertices = path.vertices
+ xs, ys = vertices[:, 0], vertices[:, 1]
+ xs = self.convert_xunits(xs)
+ ys = self.convert_yunits(ys)
+ paths.append(mpath.Path(np.column_stack([xs, ys]), path.codes))
+ xs = self.convert_xunits(offsets[:, 0])
+ ys = self.convert_yunits(offsets[:, 1])
+ offsets = np.ma.column_stack([xs, ys])
+
+ if not transform.is_affine:
+ paths = [transform.transform_path_non_affine(path)
+ for path in paths]
+ transform = transform.get_affine()
+ if not offset_trf.is_affine:
+ offsets = offset_trf.transform_non_affine(offsets)
+ # This might have changed an ndarray into a masked array.
+ offset_trf = offset_trf.get_affine()
+
+ if isinstance(offsets, np.ma.MaskedArray):
+ offsets = offsets.filled(np.nan)
+ # Changing from a masked array to nan-filled ndarray
+ # is probably most efficient at this point.
+
+ return transform, offset_trf, offsets, paths
+
+ @artist.allow_rasterization
+ def draw(self, renderer):
+ if not self.get_visible():
+ return
+ renderer.open_group(self.__class__.__name__, self.get_gid())
+
+ self.update_scalarmappable()
+
+ transform, offset_trf, offsets, paths = self._prepare_points()
+
+ gc = renderer.new_gc()
+ self._set_gc_clip(gc)
+ gc.set_snap(self.get_snap())
+
+ if self._hatch:
+ gc.set_hatch(self._hatch)
+ gc.set_hatch_color(self._hatch_color)
+ gc.set_hatch_linewidth(self._hatch_linewidth)
+
+ if self.get_sketch_params() is not None:
+ gc.set_sketch_params(*self.get_sketch_params())
+
+ if self.get_path_effects():
+ from matplotlib.patheffects import PathEffectRenderer
+ renderer = PathEffectRenderer(self.get_path_effects(), renderer)
+
+ # If the collection is made up of a single shape/color/stroke,
+ # it can be rendered once and blitted multiple times, using
+ # `draw_markers` rather than `draw_path_collection`. This is
+ # *much* faster for Agg, and results in smaller file sizes in
+ # PDF/SVG/PS.
+
+ trans = self.get_transforms()
+ facecolors = self.get_facecolor()
+ edgecolors = self.get_edgecolor()
+ do_single_path_optimization = False
+ if (len(paths) == 1 and len(trans) <= 1 and
+ len(facecolors) == 1 and len(edgecolors) == 1 and
+ len(self._linewidths) == 1 and
+ all(ls[1] is None for ls in self._linestyles) and
+ len(self._antialiaseds) == 1 and len(self._urls) == 1 and
+ self.get_hatch() is None):
+ if len(trans):
+ combined_transform = transforms.Affine2D(trans[0]) + transform
+ else:
+ combined_transform = transform
+ extents = paths[0].get_extents(combined_transform)
+ if (extents.width < self.get_figure(root=True).bbox.width
+ and extents.height < self.get_figure(root=True).bbox.height):
+ do_single_path_optimization = True
+
+ if self._joinstyle:
+ gc.set_joinstyle(self._joinstyle)
+
+ if self._capstyle:
+ gc.set_capstyle(self._capstyle)
+
+ if do_single_path_optimization:
+ gc.set_foreground(tuple(edgecolors[0]))
+ gc.set_linewidth(self._linewidths[0])
+ gc.set_dashes(*self._linestyles[0])
+ gc.set_antialiased(self._antialiaseds[0])
+ gc.set_url(self._urls[0])
+ renderer.draw_markers(
+ gc, paths[0], combined_transform.frozen(),
+ mpath.Path(offsets), offset_trf, tuple(facecolors[0]))
+ else:
+ if self._gapcolor is not None:
+ # First draw paths within the gaps.
+ ipaths, ilinestyles = self._get_inverse_paths_linestyles()
+ renderer.draw_path_collection(
+ gc, transform.frozen(), ipaths,
+ self.get_transforms(), offsets, offset_trf,
+ [mcolors.to_rgba("none")], self._gapcolor,
+ self._linewidths, ilinestyles,
+ self._antialiaseds, self._urls,
+ "screen")
+
+ renderer.draw_path_collection(
+ gc, transform.frozen(), paths,
+ self.get_transforms(), offsets, offset_trf,
+ self.get_facecolor(), self.get_edgecolor(),
+ self._linewidths, self._linestyles,
+ self._antialiaseds, self._urls,
+ "screen") # offset_position, kept for backcompat.
+
+ gc.restore()
+ renderer.close_group(self.__class__.__name__)
+ self.stale = False
+
+ def set_pickradius(self, pickradius):
+ """
+ Set the pick radius used for containment tests.
+
+ Parameters
+ ----------
+ pickradius : float
+ Pick radius, in points.
+ """
+ if not isinstance(pickradius, Real):
+ raise ValueError(
+ f"pickradius must be a real-valued number, not {pickradius!r}")
+ self._pickradius = pickradius
+
+ def get_pickradius(self):
+ return self._pickradius
+
+ def contains(self, mouseevent):
+ """
+ Test whether the mouse event occurred in the collection.
+
+ Returns ``bool, dict(ind=itemlist)``, where every item in itemlist
+ contains the event.
+ """
+ if self._different_canvas(mouseevent) or not self.get_visible():
+ return False, {}
+ pickradius = (
+ float(self._picker)
+ if isinstance(self._picker, Number) and
+ self._picker is not True # the bool, not just nonzero or 1
+ else self._pickradius)
+ if self.axes:
+ self.axes._unstale_viewLim()
+ transform, offset_trf, offsets, paths = self._prepare_points()
+ # Tests if the point is contained on one of the polygons formed
+ # by the control points of each of the paths. A point is considered
+ # "on" a path if it would lie within a stroke of width 2*pickradius
+ # following the path. If pickradius <= 0, then we instead simply check
+ # if the point is *inside* of the path instead.
+ ind = _path.point_in_path_collection(
+ mouseevent.x, mouseevent.y, pickradius,
+ transform.frozen(), paths, self.get_transforms(),
+ offsets, offset_trf, pickradius <= 0)
+ return len(ind) > 0, dict(ind=ind)
+
+ def set_urls(self, urls):
+ """
+ Parameters
+ ----------
+ urls : list of str or None
+
+ Notes
+ -----
+ URLs are currently only implemented by the SVG backend. They are
+ ignored by all other backends.
+ """
+ self._urls = urls if urls is not None else [None]
+ self.stale = True
+
+ def get_urls(self):
+ """
+ Return a list of URLs, one for each element of the collection.
+
+ The list contains *None* for elements without a URL. See
+ :doc:`/gallery/misc/hyperlinks_sgskip` for an example.
+ """
+ return self._urls
+
+ def set_hatch(self, hatch):
+ r"""
+ Set the hatching pattern
+
+ *hatch* can be one of::
+
+ / - diagonal hatching
+ \ - back diagonal
+ | - vertical
+ - - horizontal
+ + - crossed
+ x - crossed diagonal
+ o - small circle
+ O - large circle
+ . - dots
+ * - stars
+
+ Letters can be combined, in which case all the specified
+ hatchings are done. If same letter repeats, it increases the
+ density of hatching of that pattern.
+
+ Unlike other properties such as linewidth and colors, hatching
+ can only be specified for the collection as a whole, not separately
+ for each member.
+
+ Parameters
+ ----------
+ hatch : {'/', '\\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
+ """
+ # Use validate_hatch(list) after deprecation.
+ mhatch._validate_hatch_pattern(hatch)
+ self._hatch = hatch
+ self.stale = True
+
+ def get_hatch(self):
+ """Return the current hatching pattern."""
+ return self._hatch
+
+ def set_hatch_linewidth(self, lw):
+ """Set the hatch linewidth."""
+ self._hatch_linewidth = lw
+
+ def get_hatch_linewidth(self):
+ """Return the hatch linewidth."""
+ return self._hatch_linewidth
+
+ def set_offsets(self, offsets):
+ """
+ Set the offsets for the collection.
+
+ Parameters
+ ----------
+ offsets : (N, 2) or (2,) array-like
+ """
+ offsets = np.asanyarray(offsets)
+ if offsets.shape == (2,): # Broadcast (2,) -> (1, 2) but nothing else.
+ offsets = offsets[None, :]
+ cstack = (np.ma.column_stack if isinstance(offsets, np.ma.MaskedArray)
+ else np.column_stack)
+ self._offsets = cstack(
+ (np.asanyarray(self.convert_xunits(offsets[:, 0]), float),
+ np.asanyarray(self.convert_yunits(offsets[:, 1]), float)))
+ self.stale = True
+
+ def get_offsets(self):
+ """Return the offsets for the collection."""
+ # Default to zeros in the no-offset (None) case
+ return np.zeros((1, 2)) if self._offsets is None else self._offsets
+
+ def _get_default_linewidth(self):
+ # This may be overridden in a subclass.
+ return mpl.rcParams['patch.linewidth'] # validated as float
+
+ def set_linewidth(self, lw):
+ """
+ Set the linewidth(s) for the collection. *lw* can be a scalar
+ or a sequence; if it is a sequence the patches will cycle
+ through the sequence
+
+ Parameters
+ ----------
+ lw : float or list of floats
+ """
+ if lw is None:
+ lw = self._get_default_linewidth()
+ # get the un-scaled/broadcast lw
+ self._us_lw = np.atleast_1d(lw)
+
+ # scale all of the dash patterns.
+ self._linewidths, self._linestyles = self._bcast_lwls(
+ self._us_lw, self._us_linestyles)
+ self.stale = True
+
+ def set_linestyle(self, ls):
+ """
+ Set the linestyle(s) for the collection.
+
+ =========================== =================
+ linestyle description
+ =========================== =================
+ ``'-'`` or ``'solid'`` solid line
+ ``'--'`` or ``'dashed'`` dashed line
+ ``'-.'`` or ``'dashdot'`` dash-dotted line
+ ``':'`` or ``'dotted'`` dotted line
+ =========================== =================
+
+ 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 : str or tuple or list thereof
+ Valid values for individual linestyles include {'-', '--', '-.',
+ ':', '', (offset, on-off-seq)}. See `.Line2D.set_linestyle` for a
+ complete description.
+ """
+ # get the list of raw 'unscaled' dash patterns
+ self._us_linestyles = mlines._get_dash_patterns(ls)
+
+ # broadcast and scale the lw and dash patterns
+ self._linewidths, self._linestyles = self._bcast_lwls(
+ self._us_lw, self._us_linestyles)
+
+ @_docstring.interpd
+ def set_capstyle(self, cs):
+ """
+ Set the `.CapStyle` for the collection (for all its elements).
+
+ Parameters
+ ----------
+ cs : `.CapStyle` or %(CapStyle)s
+ """
+ self._capstyle = CapStyle(cs)
+
+ @_docstring.interpd
+ def get_capstyle(self):
+ """
+ Return the cap style for the collection (for all its elements).
+
+ Returns
+ -------
+ %(CapStyle)s or None
+ """
+ return self._capstyle.name if self._capstyle else None
+
+ @_docstring.interpd
+ def set_joinstyle(self, js):
+ """
+ Set the `.JoinStyle` for the collection (for all its elements).
+
+ Parameters
+ ----------
+ js : `.JoinStyle` or %(JoinStyle)s
+ """
+ self._joinstyle = JoinStyle(js)
+
+ @_docstring.interpd
+ def get_joinstyle(self):
+ """
+ Return the join style for the collection (for all its elements).
+
+ Returns
+ -------
+ %(JoinStyle)s or None
+ """
+ return self._joinstyle.name if self._joinstyle else None
+
+ @staticmethod
+ def _bcast_lwls(linewidths, dashes):
+ """
+ Internal helper function to broadcast + scale ls/lw
+
+ In the collection drawing code, the linewidth and linestyle are cycled
+ through as circular buffers (via ``v[i % len(v)]``). Thus, if we are
+ going to scale the dash pattern at set time (not draw time) we need to
+ do the broadcasting now and expand both lists to be the same length.
+
+ Parameters
+ ----------
+ linewidths : list
+ line widths of collection
+ dashes : list
+ dash specification (offset, (dash pattern tuple))
+
+ Returns
+ -------
+ linewidths, dashes : list
+ Will be the same length, dashes are scaled by paired linewidth
+ """
+ if mpl.rcParams['_internal.classic_mode']:
+ return linewidths, dashes
+ # make sure they are the same length so we can zip them
+ if len(dashes) != len(linewidths):
+ l_dashes = len(dashes)
+ l_lw = len(linewidths)
+ gcd = math.gcd(l_dashes, l_lw)
+ dashes = list(dashes) * (l_lw // gcd)
+ linewidths = list(linewidths) * (l_dashes // gcd)
+
+ # scale the dash patterns
+ dashes = [mlines._scale_dashes(o, d, lw)
+ for (o, d), lw in zip(dashes, linewidths)]
+
+ return linewidths, dashes
+
+ def get_antialiased(self):
+ """
+ Get the antialiasing state for rendering.
+
+ Returns
+ -------
+ array of bools
+ """
+ return self._antialiaseds
+
+ def set_antialiased(self, aa):
+ """
+ Set the antialiasing state for rendering.
+
+ Parameters
+ ----------
+ aa : bool or list of bools
+ """
+ if aa is None:
+ aa = self._get_default_antialiased()
+ self._antialiaseds = np.atleast_1d(np.asarray(aa, bool))
+ self.stale = True
+
+ def _get_default_antialiased(self):
+ # This may be overridden in a subclass.
+ return mpl.rcParams['patch.antialiased']
+
+ def set_color(self, c):
+ """
+ Set both the edgecolor and the facecolor.
+
+ Parameters
+ ----------
+ c : :mpltype:`color` or list of RGBA tuples
+
+ See Also
+ --------
+ Collection.set_facecolor, Collection.set_edgecolor
+ For setting the edge or face color individually.
+ """
+ self.set_facecolor(c)
+ self.set_edgecolor(c)
+
+ def _get_default_facecolor(self):
+ # This may be overridden in a subclass.
+ return mpl.rcParams['patch.facecolor']
+
+ def _set_facecolor(self, c):
+ if c is None:
+ c = self._get_default_facecolor()
+
+ self._facecolors = mcolors.to_rgba_array(c, self._alpha)
+ self.stale = True
+
+ def set_facecolor(self, c):
+ """
+ Set the facecolor(s) of the collection. *c* can be a color (all patches
+ have same color), or a sequence of colors; if it is a sequence the
+ patches will cycle through the sequence.
+
+ If *c* is 'none', the patch will not be filled.
+
+ Parameters
+ ----------
+ c : :mpltype:`color` or list of :mpltype:`color`
+ """
+ if isinstance(c, str) and c.lower() in ("none", "face"):
+ c = c.lower()
+ self._original_facecolor = c
+ self._set_facecolor(c)
+
+ def get_facecolor(self):
+ return self._facecolors
+
+ def get_edgecolor(self):
+ if cbook._str_equal(self._edgecolors, 'face'):
+ return self.get_facecolor()
+ else:
+ return self._edgecolors
+
+ def _get_default_edgecolor(self):
+ # This may be overridden in a subclass.
+ return mpl.rcParams['patch.edgecolor']
+
+ def _set_edgecolor(self, c):
+ set_hatch_color = True
+ if c is None:
+ if (mpl.rcParams['patch.force_edgecolor']
+ or self._edge_default
+ or cbook._str_equal(self._original_facecolor, 'none')):
+ c = self._get_default_edgecolor()
+ else:
+ c = 'none'
+ set_hatch_color = False
+ if cbook._str_lower_equal(c, 'face'):
+ self._edgecolors = 'face'
+ self.stale = True
+ return
+ self._edgecolors = mcolors.to_rgba_array(c, self._alpha)
+ if set_hatch_color and len(self._edgecolors):
+ self._hatch_color = tuple(self._edgecolors[0])
+ self.stale = True
+
+ def set_edgecolor(self, c):
+ """
+ Set the edgecolor(s) of the collection.
+
+ Parameters
+ ----------
+ c : :mpltype:`color` or list of :mpltype:`color` or 'face'
+ The collection edgecolor(s). If a sequence, the patches cycle
+ through it. If 'face', match the facecolor.
+ """
+ # We pass through a default value for use in LineCollection.
+ # This allows us to maintain None as the default indicator in
+ # _original_edgecolor.
+ if isinstance(c, str) and c.lower() in ("none", "face"):
+ c = c.lower()
+ self._original_edgecolor = c
+ self._set_edgecolor(c)
+
+ def set_alpha(self, alpha):
+ """
+ Set the transparency of the collection.
+
+ Parameters
+ ----------
+ alpha : float or array of float or None
+ If not None, *alpha* values must be between 0 and 1, inclusive.
+ If an array is provided, its length must match the number of
+ elements in the collection. Masked values and nans are not
+ supported.
+ """
+ artist.Artist._set_alpha_for_array(self, alpha)
+ self._set_facecolor(self._original_facecolor)
+ self._set_edgecolor(self._original_edgecolor)
+
+ set_alpha.__doc__ = artist.Artist._set_alpha_for_array.__doc__
+
+ def get_linewidth(self):
+ return self._linewidths
+
+ def get_linestyle(self):
+ return self._linestyles
+
+ def _set_mappable_flags(self):
+ """
+ Determine whether edges and/or faces are color-mapped.
+
+ This is a helper for update_scalarmappable.
+ It sets Boolean flags '_edge_is_mapped' and '_face_is_mapped'.
+
+ Returns
+ -------
+ mapping_change : bool
+ True if either flag is True, or if a flag has changed.
+ """
+ # The flags are initialized to None to ensure this returns True
+ # the first time it is called.
+ edge0 = self._edge_is_mapped
+ face0 = self._face_is_mapped
+ # After returning, the flags must be Booleans, not None.
+ self._edge_is_mapped = False
+ self._face_is_mapped = False
+ if self._A is not None:
+ if not cbook._str_equal(self._original_facecolor, 'none'):
+ self._face_is_mapped = True
+ if cbook._str_equal(self._original_edgecolor, 'face'):
+ self._edge_is_mapped = True
+ else:
+ if self._original_edgecolor is None:
+ self._edge_is_mapped = True
+
+ mapped = self._face_is_mapped or self._edge_is_mapped
+ changed = (edge0 is None or face0 is None
+ or self._edge_is_mapped != edge0
+ or self._face_is_mapped != face0)
+ return mapped or changed
+
+ def update_scalarmappable(self):
+ """
+ Update colors from the scalar mappable array, if any.
+
+ Assign colors to edges and faces based on the array and/or
+ colors that were directly set, as appropriate.
+ """
+ if not self._set_mappable_flags():
+ return
+ # Allow possibility to call 'self.set_array(None)'.
+ if self._A is not None:
+ # QuadMesh can map 2d arrays (but pcolormesh supplies 1d array)
+ if self._A.ndim > 1 and not isinstance(self, _MeshData):
+ raise ValueError('Collections can only map rank 1 arrays')
+ if np.iterable(self._alpha):
+ if self._alpha.size != self._A.size:
+ raise ValueError(
+ f'Data array shape, {self._A.shape} '
+ 'is incompatible with alpha array shape, '
+ f'{self._alpha.shape}. '
+ 'This can occur with the deprecated '
+ 'behavior of the "flat" shading option, '
+ 'in which a row and/or column of the data '
+ 'array is dropped.')
+ # pcolormesh, scatter, maybe others flatten their _A
+ self._alpha = self._alpha.reshape(self._A.shape)
+ self._mapped_colors = self.to_rgba(self._A, self._alpha)
+
+ if self._face_is_mapped:
+ self._facecolors = self._mapped_colors
+ else:
+ self._set_facecolor(self._original_facecolor)
+ if self._edge_is_mapped:
+ self._edgecolors = self._mapped_colors
+ else:
+ self._set_edgecolor(self._original_edgecolor)
+ self.stale = True
+
+ def get_fill(self):
+ """Return whether face is colored."""
+ return not cbook._str_lower_equal(self._original_facecolor, "none")
+
+ def update_from(self, other):
+ """Copy properties from other to self."""
+
+ artist.Artist.update_from(self, other)
+ self._antialiaseds = other._antialiaseds
+ self._mapped_colors = other._mapped_colors
+ self._edge_is_mapped = other._edge_is_mapped
+ self._original_edgecolor = other._original_edgecolor
+ self._edgecolors = other._edgecolors
+ self._face_is_mapped = other._face_is_mapped
+ self._original_facecolor = other._original_facecolor
+ self._facecolors = other._facecolors
+ self._linewidths = other._linewidths
+ self._linestyles = other._linestyles
+ self._us_linestyles = other._us_linestyles
+ self._pickradius = other._pickradius
+ self._hatch = other._hatch
+
+ # update_from for scalarmappable
+ self._A = other._A
+ self.norm = other.norm
+ self.cmap = other.cmap
+ self.stale = True
+
+
+class _CollectionWithSizes(Collection):
+ """
+ Base class for collections that have an array of sizes.
+ """
+ _factor = 1.0
+
+ def get_sizes(self):
+ """
+ Return the sizes ('areas') of the elements in the collection.
+
+ Returns
+ -------
+ array
+ The 'area' of each element.
+ """
+ return self._sizes
+
+ def set_sizes(self, sizes, dpi=72.0):
+ """
+ Set the sizes of each member of the collection.
+
+ Parameters
+ ----------
+ sizes : `numpy.ndarray` or None
+ The size to set for each element of the collection. The
+ value is the 'area' of the element.
+ dpi : float, default: 72
+ The dpi of the canvas.
+ """
+ if sizes is None:
+ self._sizes = np.array([])
+ self._transforms = np.empty((0, 3, 3))
+ else:
+ self._sizes = np.asarray(sizes)
+ self._transforms = np.zeros((len(self._sizes), 3, 3))
+ scale = np.sqrt(self._sizes) * dpi / 72.0 * self._factor
+ self._transforms[:, 0, 0] = scale
+ self._transforms[:, 1, 1] = scale
+ self._transforms[:, 2, 2] = 1.0
+ self.stale = True
+
+ @artist.allow_rasterization
+ def draw(self, renderer):
+ self.set_sizes(self._sizes, self.get_figure(root=True).dpi)
+ super().draw(renderer)
+
+
+class PathCollection(_CollectionWithSizes):
+ r"""
+ A collection of `~.path.Path`\s, as created by e.g. `~.Axes.scatter`.
+ """
+
+ def __init__(self, paths, sizes=None, **kwargs):
+ """
+ Parameters
+ ----------
+ paths : list of `.path.Path`
+ The paths that will make up the `.Collection`.
+ sizes : array-like
+ The factor by which to scale each drawn `~.path.Path`. One unit
+ squared in the Path's data space is scaled to be ``sizes**2``
+ points when rendered.
+ **kwargs
+ Forwarded to `.Collection`.
+ """
+
+ super().__init__(**kwargs)
+ self.set_paths(paths)
+ self.set_sizes(sizes)
+ self.stale = True
+
+ def get_paths(self):
+ return self._paths
+
+ def legend_elements(self, prop="colors", num="auto",
+ fmt=None, func=lambda x: x, **kwargs):
+ """
+ Create legend handles and labels for a PathCollection.
+
+ Each legend handle is a `.Line2D` representing the Path that was drawn,
+ and each label is a string that represents the Path.
+
+ This is useful for obtaining a legend for a `~.Axes.scatter` plot;
+ e.g.::
+
+ scatter = plt.scatter([1, 2, 3], [4, 5, 6], c=[7, 2, 3], num=None)
+ plt.legend(*scatter.legend_elements())
+
+ creates three legend elements, one for each color with the numerical
+ values passed to *c* as the labels.
+
+ Also see the :ref:`automatedlegendcreation` example.
+
+ Parameters
+ ----------
+ prop : {"colors", "sizes"}, default: "colors"
+ If "colors", the legend handles will show the different colors of
+ the collection. If "sizes", the legend will show the different
+ sizes. To set both, use *kwargs* to directly edit the `.Line2D`
+ properties.
+ num : int, None, "auto" (default), array-like, or `~.ticker.Locator`
+ Target number of elements to create.
+ If None, use all unique elements of the mappable array. If an
+ integer, target to use *num* elements in the normed range.
+ If *"auto"*, try to determine which option better suits the nature
+ of the data.
+ The number of created elements may slightly deviate from *num* due
+ to a `~.ticker.Locator` being used to find useful locations.
+ If a list or array, use exactly those elements for the legend.
+ Finally, a `~.ticker.Locator` can be provided.
+ fmt : str, `~matplotlib.ticker.Formatter`, or None (default)
+ The format or formatter to use for the labels. If a string must be
+ a valid input for a `.StrMethodFormatter`. If None (the default),
+ use a `.ScalarFormatter`.
+ func : function, default: ``lambda x: x``
+ Function to calculate the labels. Often the size (or color)
+ argument to `~.Axes.scatter` will have been pre-processed by the
+ user using a function ``s = f(x)`` to make the markers visible;
+ e.g. ``size = np.log10(x)``. Providing the inverse of this
+ function here allows that pre-processing to be inverted, so that
+ the legend labels have the correct values; e.g. ``func = lambda
+ x: 10**x``.
+ **kwargs
+ Allowed keyword arguments are *color* and *size*. E.g. it may be
+ useful to set the color of the markers if *prop="sizes"* is used;
+ similarly to set the size of the markers if *prop="colors"* is
+ used. Any further parameters are passed onto the `.Line2D`
+ instance. This may be useful to e.g. specify a different
+ *markeredgecolor* or *alpha* for the legend handles.
+
+ Returns
+ -------
+ handles : list of `.Line2D`
+ Visual representation of each element of the legend.
+ labels : list of str
+ The string labels for elements of the legend.
+ """
+ handles = []
+ labels = []
+ hasarray = self.get_array() is not None
+ if fmt is None:
+ fmt = mpl.ticker.ScalarFormatter(useOffset=False, useMathText=True)
+ elif isinstance(fmt, str):
+ fmt = mpl.ticker.StrMethodFormatter(fmt)
+ fmt.create_dummy_axis()
+
+ if prop == "colors":
+ if not hasarray:
+ warnings.warn("Collection without array used. Make sure to "
+ "specify the values to be colormapped via the "
+ "`c` argument.")
+ return handles, labels
+ u = np.unique(self.get_array())
+ size = kwargs.pop("size", mpl.rcParams["lines.markersize"])
+ elif prop == "sizes":
+ u = np.unique(self.get_sizes())
+ color = kwargs.pop("color", "k")
+ else:
+ raise ValueError("Valid values for `prop` are 'colors' or "
+ f"'sizes'. You supplied '{prop}' instead.")
+
+ fu = func(u)
+ fmt.axis.set_view_interval(fu.min(), fu.max())
+ fmt.axis.set_data_interval(fu.min(), fu.max())
+ if num == "auto":
+ num = 9
+ if len(u) <= num:
+ num = None
+ if num is None:
+ values = u
+ label_values = func(values)
+ else:
+ if prop == "colors":
+ arr = self.get_array()
+ elif prop == "sizes":
+ arr = self.get_sizes()
+ if isinstance(num, mpl.ticker.Locator):
+ loc = num
+ elif np.iterable(num):
+ loc = mpl.ticker.FixedLocator(num)
+ else:
+ num = int(num)
+ loc = mpl.ticker.MaxNLocator(nbins=num, min_n_ticks=num-1,
+ steps=[1, 2, 2.5, 3, 5, 6, 8, 10])
+ label_values = loc.tick_values(func(arr).min(), func(arr).max())
+ cond = ((label_values >= func(arr).min()) &
+ (label_values <= func(arr).max()))
+ label_values = label_values[cond]
+ yarr = np.linspace(arr.min(), arr.max(), 256)
+ xarr = func(yarr)
+ ix = np.argsort(xarr)
+ values = np.interp(label_values, xarr[ix], yarr[ix])
+
+ kw = {"markeredgewidth": self.get_linewidths()[0],
+ "alpha": self.get_alpha(),
+ **kwargs}
+
+ for val, lab in zip(values, label_values):
+ if prop == "colors":
+ color = self.cmap(self.norm(val))
+ elif prop == "sizes":
+ size = np.sqrt(val)
+ if np.isclose(size, 0.0):
+ continue
+ h = mlines.Line2D([0], [0], ls="", color=color, ms=size,
+ marker=self.get_paths()[0], **kw)
+ handles.append(h)
+ if hasattr(fmt, "set_locs"):
+ fmt.set_locs(label_values)
+ l = fmt(lab)
+ labels.append(l)
+
+ return handles, labels
+
+
+class PolyCollection(_CollectionWithSizes):
+
+ def __init__(self, verts, sizes=None, *, closed=True, **kwargs):
+ """
+ Parameters
+ ----------
+ verts : list of array-like
+ The sequence of polygons [*verts0*, *verts1*, ...] where each
+ element *verts_i* defines the vertices of polygon *i* as a 2D
+ array-like of shape (M, 2).
+ sizes : array-like, default: None
+ Squared scaling factors for the polygons. The coordinates of each
+ polygon *verts_i* are multiplied by the square-root of the
+ corresponding entry in *sizes* (i.e., *sizes* specify the scaling
+ of areas). The scaling is applied before the Artist master
+ transform.
+ closed : bool, default: True
+ Whether the polygon should be closed by adding a CLOSEPOLY
+ connection at the end.
+ **kwargs
+ Forwarded to `.Collection`.
+ """
+ super().__init__(**kwargs)
+ self.set_sizes(sizes)
+ self.set_verts(verts, closed)
+ self.stale = True
+
+ def set_verts(self, verts, closed=True):
+ """
+ Set the vertices of the polygons.
+
+ Parameters
+ ----------
+ verts : list of array-like
+ The sequence of polygons [*verts0*, *verts1*, ...] where each
+ element *verts_i* defines the vertices of polygon *i* as a 2D
+ array-like of shape (M, 2).
+ closed : bool, default: True
+ Whether the polygon should be closed by adding a CLOSEPOLY
+ connection at the end.
+ """
+ self.stale = True
+ if isinstance(verts, np.ma.MaskedArray):
+ verts = verts.astype(float).filled(np.nan)
+
+ # No need to do anything fancy if the path isn't closed.
+ if not closed:
+ self._paths = [mpath.Path(xy) for xy in verts]
+ return
+
+ # Fast path for arrays
+ if isinstance(verts, np.ndarray) and len(verts.shape) == 3:
+ verts_pad = np.concatenate((verts, verts[:, :1]), axis=1)
+ # Creating the codes once is much faster than having Path do it
+ # separately each time by passing closed=True.
+ codes = np.empty(verts_pad.shape[1], dtype=mpath.Path.code_type)
+ codes[:] = mpath.Path.LINETO
+ codes[0] = mpath.Path.MOVETO
+ codes[-1] = mpath.Path.CLOSEPOLY
+ self._paths = [mpath.Path(xy, codes) for xy in verts_pad]
+ return
+
+ self._paths = []
+ for xy in verts:
+ if len(xy):
+ self._paths.append(mpath.Path._create_closed(xy))
+ else:
+ self._paths.append(mpath.Path(xy))
+
+ set_paths = set_verts
+
+ def set_verts_and_codes(self, verts, codes):
+ """Initialize vertices with path codes."""
+ if len(verts) != len(codes):
+ raise ValueError("'codes' must be a 1D list or array "
+ "with the same length of 'verts'")
+ self._paths = [mpath.Path(xy, cds) if len(xy) else mpath.Path(xy)
+ for xy, cds in zip(verts, codes)]
+ self.stale = True
+
+
+class FillBetweenPolyCollection(PolyCollection):
+ """
+ `.PolyCollection` that fills the area between two x- or y-curves.
+ """
+ def __init__(
+ self, t_direction, t, f1, f2, *,
+ where=None, interpolate=False, step=None, **kwargs):
+ """
+ Parameters
+ ----------
+ t_direction : {{'x', 'y'}}
+ The axes on which the variable lies.
+
+ - 'x': the curves are ``(t, f1)`` and ``(t, f2)``.
+ - 'y': the curves are ``(f1, t)`` and ``(f2, t)``.
+
+ t : array-like
+ The ``t_direction`` coordinates of the nodes defining the curves.
+
+ f1 : array-like or float
+ The other coordinates of the nodes defining the first curve.
+
+ f2 : array-like or float
+ The other coordinates of the nodes defining the second curve.
+
+ where : array-like of bool, optional
+ Define *where* to exclude some {dir} regions from being filled.
+ The filled regions are defined by the coordinates ``t[where]``.
+ More precisely, fill between ``t[i]`` and ``t[i+1]`` if
+ ``where[i] and where[i+1]``. Note that this definition implies
+ that an isolated *True* value between two *False* values in *where*
+ will not result in filling. Both sides of the *True* position
+ remain unfilled due to the adjacent *False* values.
+
+ interpolate : bool, default: False
+ This option is only relevant if *where* is used and the two curves
+ are crossing each other.
+
+ Semantically, *where* is often used for *f1* > *f2* or
+ similar. By default, the nodes of the polygon defining the filled
+ region will only be placed at the positions in the *t* array.
+ Such a polygon cannot describe the above semantics close to the
+ intersection. The t-sections containing the intersection are
+ simply clipped.
+
+ Setting *interpolate* to *True* will calculate the actual
+ intersection point and extend the filled region up to this point.
+
+ step : {{'pre', 'post', 'mid'}}, optional
+ Define *step* if the filling should be a step function,
+ i.e. constant in between *t*. The value determines where the
+ step will occur:
+
+ - 'pre': The f value is continued constantly to the left from
+ every *t* position, i.e. the interval ``(t[i-1], t[i]]`` has the
+ value ``f[i]``.
+ - 'post': The y value is continued constantly to the right from
+ every *x* position, i.e. the interval ``[t[i], t[i+1])`` has the
+ value ``f[i]``.
+ - 'mid': Steps occur half-way between the *t* positions.
+
+ **kwargs
+ Forwarded to `.PolyCollection`.
+
+ See Also
+ --------
+ .Axes.fill_between, .Axes.fill_betweenx
+ """
+ self.t_direction = t_direction
+ self._interpolate = interpolate
+ self._step = step
+ verts = self._make_verts(t, f1, f2, where)
+ super().__init__(verts, **kwargs)
+
+ @staticmethod
+ def _f_dir_from_t(t_direction):
+ """The direction that is other than `t_direction`."""
+ if t_direction == "x":
+ return "y"
+ elif t_direction == "y":
+ return "x"
+ else:
+ msg = f"t_direction must be 'x' or 'y', got {t_direction!r}"
+ raise ValueError(msg)
+
+ @property
+ def _f_direction(self):
+ """The direction that is other than `self.t_direction`."""
+ return self._f_dir_from_t(self.t_direction)
+
+ def set_data(self, t, f1, f2, *, where=None):
+ """
+ Set new values for the two bounding curves.
+
+ Parameters
+ ----------
+ t : array-like
+ The ``self.t_direction`` coordinates of the nodes defining the curves.
+
+ f1 : array-like or float
+ The other coordinates of the nodes defining the first curve.
+
+ f2 : array-like or float
+ The other coordinates of the nodes defining the second curve.
+
+ where : array-like of bool, optional
+ Define *where* to exclude some {dir} regions from being filled.
+ The filled regions are defined by the coordinates ``t[where]``.
+ More precisely, fill between ``t[i]`` and ``t[i+1]`` if
+ ``where[i] and where[i+1]``. Note that this definition implies
+ that an isolated *True* value between two *False* values in *where*
+ will not result in filling. Both sides of the *True* position
+ remain unfilled due to the adjacent *False* values.
+
+ See Also
+ --------
+ .PolyCollection.set_verts, .Line2D.set_data
+ """
+ t, f1, f2 = self.axes._fill_between_process_units(
+ self.t_direction, self._f_direction, t, f1, f2)
+
+ verts = self._make_verts(t, f1, f2, where)
+ self.set_verts(verts)
+
+ def get_datalim(self, transData):
+ """Calculate the data limits and return them as a `.Bbox`."""
+ datalim = transforms.Bbox.null()
+ datalim.update_from_data_xy((self.get_transform() - transData).transform(
+ np.concatenate([self._bbox, [self._bbox.minpos]])))
+ return datalim
+
+ def _make_verts(self, t, f1, f2, where):
+ """
+ Make verts that can be forwarded to `.PolyCollection`.
+ """
+ self._validate_shapes(self.t_direction, self._f_direction, t, f1, f2)
+
+ where = self._get_data_mask(t, f1, f2, where)
+ t, f1, f2 = np.broadcast_arrays(np.atleast_1d(t), f1, f2, subok=True)
+
+ self._bbox = transforms.Bbox.null()
+ self._bbox.update_from_data_xy(self._fix_pts_xy_order(np.concatenate([
+ np.stack((t[where], f[where]), axis=-1) for f in (f1, f2)])))
+
+ return [
+ self._make_verts_for_region(t, f1, f2, idx0, idx1)
+ for idx0, idx1 in cbook.contiguous_regions(where)
+ ]
+
+ def _get_data_mask(self, t, f1, f2, where):
+ """
+ Return a bool array, with True at all points that should eventually be rendered.
+
+ The array is True at a point if none of the data inputs
+ *t*, *f1*, *f2* is masked and if the input *where* is true at that point.
+ """
+ if where is None:
+ where = True
+ else:
+ where = np.asarray(where, dtype=bool)
+ if where.size != t.size:
+ msg = "where size ({}) does not match {!r} size ({})".format(
+ where.size, self.t_direction, t.size)
+ raise ValueError(msg)
+ return where & ~functools.reduce(
+ np.logical_or, map(np.ma.getmaskarray, [t, f1, f2]))
+
+ @staticmethod
+ def _validate_shapes(t_dir, f_dir, t, f1, f2):
+ """Validate that t, f1 and f2 are 1-dimensional and have the same length."""
+ names = (d + s for d, s in zip((t_dir, f_dir, f_dir), ("", "1", "2")))
+ for name, array in zip(names, [t, f1, f2]):
+ if array.ndim > 1:
+ raise ValueError(f"{name!r} is not 1-dimensional")
+ if t.size > 1 and array.size > 1 and t.size != array.size:
+ msg = "{!r} has size {}, but {!r} has an unequal size of {}".format(
+ t_dir, t.size, name, array.size)
+ raise ValueError(msg)
+
+ def _make_verts_for_region(self, t, f1, f2, idx0, idx1):
+ """
+ Make ``verts`` for a contiguous region between ``idx0`` and ``idx1``, taking
+ into account ``step`` and ``interpolate``.
+ """
+ t_slice = t[idx0:idx1]
+ f1_slice = f1[idx0:idx1]
+ f2_slice = f2[idx0:idx1]
+ if self._step is not None:
+ step_func = cbook.STEP_LOOKUP_MAP["steps-" + self._step]
+ t_slice, f1_slice, f2_slice = step_func(t_slice, f1_slice, f2_slice)
+
+ if self._interpolate:
+ start = self._get_interpolating_points(t, f1, f2, idx0)
+ end = self._get_interpolating_points(t, f1, f2, idx1)
+ else:
+ # Handle scalar f2 (e.g. 0): the fill should go all
+ # the way down to 0 even if none of the dep1 sample points do.
+ start = t_slice[0], f2_slice[0]
+ end = t_slice[-1], f2_slice[-1]
+
+ pts = np.concatenate((
+ np.asarray([start]),
+ np.stack((t_slice, f1_slice), axis=-1),
+ np.asarray([end]),
+ np.stack((t_slice, f2_slice), axis=-1)[::-1]))
+
+ return self._fix_pts_xy_order(pts)
+
+ @classmethod
+ def _get_interpolating_points(cls, t, f1, f2, idx):
+ """Calculate interpolating points."""
+ im1 = max(idx - 1, 0)
+ t_values = t[im1:idx+1]
+ diff_values = f1[im1:idx+1] - f2[im1:idx+1]
+ f1_values = f1[im1:idx+1]
+
+ if len(diff_values) == 2:
+ if np.ma.is_masked(diff_values[1]):
+ return t[im1], f1[im1]
+ elif np.ma.is_masked(diff_values[0]):
+ return t[idx], f1[idx]
+
+ diff_root_t = cls._get_diff_root(0, diff_values, t_values)
+ diff_root_f = cls._get_diff_root(diff_root_t, t_values, f1_values)
+ return diff_root_t, diff_root_f
+
+ @staticmethod
+ def _get_diff_root(x, xp, fp):
+ """Calculate diff root."""
+ order = xp.argsort()
+ return np.interp(x, xp[order], fp[order])
+
+ def _fix_pts_xy_order(self, pts):
+ """
+ Fix pts calculation results with `self.t_direction`.
+
+ In the workflow, it is assumed that `self.t_direction` is 'x'. If this
+ is not true, we need to exchange the coordinates.
+ """
+ return pts[:, ::-1] if self.t_direction == "y" else pts
+
+
+class RegularPolyCollection(_CollectionWithSizes):
+ """A collection of n-sided regular polygons."""
+
+ _path_generator = mpath.Path.unit_regular_polygon
+ _factor = np.pi ** (-1/2)
+
+ def __init__(self,
+ numsides,
+ *,
+ rotation=0,
+ sizes=(1,),
+ **kwargs):
+ """
+ Parameters
+ ----------
+ numsides : int
+ The number of sides of the polygon.
+ rotation : float
+ The rotation of the polygon in radians.
+ sizes : tuple of float
+ The area of the circle circumscribing the polygon in points^2.
+ **kwargs
+ Forwarded to `.Collection`.
+
+ Examples
+ --------
+ See :doc:`/gallery/event_handling/lasso_demo` for a complete example::
+
+ offsets = np.random.rand(20, 2)
+ facecolors = [cm.jet(x) for x in np.random.rand(20)]
+
+ collection = RegularPolyCollection(
+ numsides=5, # a pentagon
+ rotation=0, sizes=(50,),
+ facecolors=facecolors,
+ edgecolors=("black",),
+ linewidths=(1,),
+ offsets=offsets,
+ offset_transform=ax.transData,
+ )
+ """
+ super().__init__(**kwargs)
+ self.set_sizes(sizes)
+ self._numsides = numsides
+ self._paths = [self._path_generator(numsides)]
+ self._rotation = rotation
+ self.set_transform(transforms.IdentityTransform())
+
+ def get_numsides(self):
+ return self._numsides
+
+ def get_rotation(self):
+ return self._rotation
+
+ @artist.allow_rasterization
+ def draw(self, renderer):
+ self.set_sizes(self._sizes, self.get_figure(root=True).dpi)
+ self._transforms = [
+ transforms.Affine2D(x).rotate(-self._rotation).get_matrix()
+ for x in self._transforms
+ ]
+ # Explicitly not super().draw, because set_sizes must be called before
+ # updating self._transforms.
+ Collection.draw(self, renderer)
+
+
+class StarPolygonCollection(RegularPolyCollection):
+ """Draw a collection of regular stars with *numsides* points."""
+ _path_generator = mpath.Path.unit_regular_star
+
+
+class AsteriskPolygonCollection(RegularPolyCollection):
+ """Draw a collection of regular asterisks with *numsides* points."""
+ _path_generator = mpath.Path.unit_regular_asterisk
+
+
+class LineCollection(Collection):
+ r"""
+ Represents a sequence of `.Line2D`\s that should be drawn together.
+
+ This class extends `.Collection` to represent a sequence of
+ `.Line2D`\s instead of just a sequence of `.Patch`\s.
+ Just as in `.Collection`, each property of a *LineCollection* may be either
+ a single value or a list of values. This list is then used cyclically for
+ each element of the LineCollection, so the property of the ``i``\th element
+ of the collection is::
+
+ prop[i % len(prop)]
+
+ The properties of each member of a *LineCollection* default to their values
+ in :rc:`lines.*` instead of :rc:`patch.*`, and the property *colors* is
+ added in place of *edgecolors*.
+ """
+
+ _edge_default = True
+
+ def __init__(self, segments, # Can be None.
+ *,
+ zorder=2, # Collection.zorder is 1
+ **kwargs
+ ):
+ """
+ Parameters
+ ----------
+ segments : list of (N, 2) array-like
+ A sequence ``[line0, line1, ...]`` where each line is a (N, 2)-shape
+ array-like containing points::
+
+ line0 = [(x0, y0), (x1, y1), ...]
+
+ Each line can contain a different number of points.
+ linewidths : float or list of float, default: :rc:`lines.linewidth`
+ The width of each line in points.
+ colors : :mpltype:`color` or list of color, default: :rc:`lines.color`
+ A sequence of RGBA tuples (e.g., arbitrary color strings, etc, not
+ allowed).
+ antialiaseds : bool or list of bool, default: :rc:`lines.antialiased`
+ Whether to use antialiasing for each line.
+ zorder : float, default: 2
+ zorder of the lines once drawn.
+
+ facecolors : :mpltype:`color` or list of :mpltype:`color`, default: 'none'
+ When setting *facecolors*, each line is interpreted as a boundary
+ for an area, implicitly closing the path from the last point to the
+ first point. The enclosed area is filled with *facecolor*.
+ In order to manually specify what should count as the "interior" of
+ each line, please use `.PathCollection` instead, where the
+ "interior" can be specified by appropriate usage of
+ `~.path.Path.CLOSEPOLY`.
+
+ **kwargs
+ Forwarded to `.Collection`.
+ """
+ # Unfortunately, mplot3d needs this explicit setting of 'facecolors'.
+ kwargs.setdefault('facecolors', 'none')
+ super().__init__(
+ zorder=zorder,
+ **kwargs)
+ self.set_segments(segments)
+
+ def set_segments(self, segments):
+ if segments is None:
+ return
+
+ self._paths = [mpath.Path(seg) if isinstance(seg, np.ma.MaskedArray)
+ else mpath.Path(np.asarray(seg, float))
+ for seg in segments]
+ self.stale = True
+
+ set_verts = set_segments # for compatibility with PolyCollection
+ set_paths = set_segments
+
+ def get_segments(self):
+ """
+ Returns
+ -------
+ list
+ List of segments in the LineCollection. Each list item contains an
+ array of vertices.
+ """
+ segments = []
+
+ for path in self._paths:
+ vertices = [
+ vertex
+ for vertex, _
+ # Never simplify here, we want to get the data-space values
+ # back and there in no way to know the "right" simplification
+ # threshold so never try.
+ in path.iter_segments(simplify=False)
+ ]
+ vertices = np.asarray(vertices)
+ segments.append(vertices)
+
+ return segments
+
+ def _get_default_linewidth(self):
+ return mpl.rcParams['lines.linewidth']
+
+ def _get_default_antialiased(self):
+ return mpl.rcParams['lines.antialiased']
+
+ def _get_default_edgecolor(self):
+ return mpl.rcParams['lines.color']
+
+ def _get_default_facecolor(self):
+ return 'none'
+
+ def set_alpha(self, alpha):
+ # docstring inherited
+ super().set_alpha(alpha)
+ if self._gapcolor is not None:
+ self.set_gapcolor(self._original_gapcolor)
+
+ def set_color(self, c):
+ """
+ Set the edgecolor(s) of the LineCollection.
+
+ Parameters
+ ----------
+ c : :mpltype:`color` or list of :mpltype:`color`
+ Single color (all lines have same color), or a
+ sequence of RGBA tuples; if it is a sequence the lines will
+ cycle through the sequence.
+ """
+ self.set_edgecolor(c)
+
+ set_colors = set_color
+
+ def get_color(self):
+ return self._edgecolors
+
+ get_colors = get_color # for compatibility with old versions
+
+ 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 list of :mpltype:`color` or None
+ The color with which to fill the gaps. If None, the gaps are
+ unfilled.
+ """
+ self._original_gapcolor = gapcolor
+ self._set_gapcolor(gapcolor)
+
+ def _set_gapcolor(self, gapcolor):
+ if gapcolor is not None:
+ gapcolor = mcolors.to_rgba_array(gapcolor, self._alpha)
+ self._gapcolor = gapcolor
+ self.stale = True
+
+ def get_gapcolor(self):
+ return self._gapcolor
+
+ def _get_inverse_paths_linestyles(self):
+ """
+ Returns the path and pattern for the gaps in the non-solid lines.
+
+ This path and pattern is the inverse of the path and pattern used to
+ construct the non-solid lines. For solid lines, we set the inverse path
+ to nans to prevent drawing an inverse line.
+ """
+ path_patterns = [
+ (mpath.Path(np.full((1, 2), np.nan)), ls)
+ if ls == (0, None) else
+ (path, mlines._get_inverse_dash_pattern(*ls))
+ for (path, ls) in
+ zip(self._paths, itertools.cycle(self._linestyles))]
+
+ return zip(*path_patterns)
+
+
+class EventCollection(LineCollection):
+ """
+ A collection of locations along a single axis at which an "event" occurred.
+
+ The events are given by a 1-dimensional array. They do not have an
+ amplitude and are displayed as parallel lines.
+ """
+
+ _edge_default = True
+
+ def __init__(self,
+ positions, # Cannot be None.
+ orientation='horizontal',
+ *,
+ lineoffset=0,
+ linelength=1,
+ linewidth=None,
+ color=None,
+ linestyle='solid',
+ antialiased=None,
+ **kwargs
+ ):
+ """
+ Parameters
+ ----------
+ positions : 1D array-like
+ Each value is an event.
+ orientation : {'horizontal', 'vertical'}, default: 'horizontal'
+ The sequence of events is plotted along this direction.
+ The marker lines of the single events are along the orthogonal
+ direction.
+ lineoffset : float, default: 0
+ The offset of the center of the markers from the origin, in the
+ direction orthogonal to *orientation*.
+ linelength : float, default: 1
+ The total height of the marker (i.e. the marker stretches from
+ ``lineoffset - linelength/2`` to ``lineoffset + linelength/2``).
+ linewidth : float or list thereof, default: :rc:`lines.linewidth`
+ The line width of the event lines, in points.
+ color : :mpltype:`color` or list of :mpltype:`color`, default: :rc:`lines.color`
+ The color of the event lines.
+ linestyle : str or tuple or list thereof, default: 'solid'
+ Valid strings are ['solid', 'dashed', 'dashdot', 'dotted',
+ '-', '--', '-.', ':']. Dash tuples should be of the form::
+
+ (offset, onoffseq),
+
+ where *onoffseq* is an even length tuple of on and off ink
+ in points.
+ antialiased : bool or list thereof, default: :rc:`lines.antialiased`
+ Whether to use antialiasing for drawing the lines.
+ **kwargs
+ Forwarded to `.LineCollection`.
+
+ Examples
+ --------
+ .. plot:: gallery/lines_bars_and_markers/eventcollection_demo.py
+ """
+ super().__init__([],
+ linewidths=linewidth, linestyles=linestyle,
+ colors=color, antialiaseds=antialiased,
+ **kwargs)
+ self._is_horizontal = True # Initial value, may be switched below.
+ self._linelength = linelength
+ self._lineoffset = lineoffset
+ self.set_orientation(orientation)
+ self.set_positions(positions)
+
+ def get_positions(self):
+ """
+ Return an array containing the floating-point values of the positions.
+ """
+ pos = 0 if self.is_horizontal() else 1
+ return [segment[0, pos] for segment in self.get_segments()]
+
+ def set_positions(self, positions):
+ """Set the positions of the events."""
+ if positions is None:
+ positions = []
+ if np.ndim(positions) != 1:
+ raise ValueError('positions must be one-dimensional')
+ lineoffset = self.get_lineoffset()
+ linelength = self.get_linelength()
+ pos_idx = 0 if self.is_horizontal() else 1
+ segments = np.empty((len(positions), 2, 2))
+ segments[:, :, pos_idx] = np.sort(positions)[:, None]
+ segments[:, 0, 1 - pos_idx] = lineoffset + linelength / 2
+ segments[:, 1, 1 - pos_idx] = lineoffset - linelength / 2
+ self.set_segments(segments)
+
+ def add_positions(self, position):
+ """Add one or more events at the specified positions."""
+ if position is None or (hasattr(position, 'len') and
+ len(position) == 0):
+ return
+ positions = self.get_positions()
+ positions = np.hstack([positions, np.asanyarray(position)])
+ self.set_positions(positions)
+ extend_positions = append_positions = add_positions
+
+ def is_horizontal(self):
+ """True if the eventcollection is horizontal, False if vertical."""
+ return self._is_horizontal
+
+ def get_orientation(self):
+ """
+ Return the orientation of the event line ('horizontal' or 'vertical').
+ """
+ return 'horizontal' if self.is_horizontal() else 'vertical'
+
+ def switch_orientation(self):
+ """
+ Switch the orientation of the event line, either from vertical to
+ horizontal or vice versus.
+ """
+ segments = self.get_segments()
+ for i, segment in enumerate(segments):
+ segments[i] = np.fliplr(segment)
+ self.set_segments(segments)
+ self._is_horizontal = not self.is_horizontal()
+ self.stale = True
+
+ def set_orientation(self, orientation):
+ """
+ Set the orientation of the event line.
+
+ Parameters
+ ----------
+ orientation : {'horizontal', 'vertical'}
+ """
+ is_horizontal = _api.check_getitem(
+ {"horizontal": True, "vertical": False},
+ orientation=orientation)
+ if is_horizontal == self.is_horizontal():
+ return
+ self.switch_orientation()
+
+ def get_linelength(self):
+ """Return the length of the lines used to mark each event."""
+ return self._linelength
+
+ def set_linelength(self, linelength):
+ """Set the length of the lines used to mark each event."""
+ if linelength == self.get_linelength():
+ return
+ lineoffset = self.get_lineoffset()
+ segments = self.get_segments()
+ pos = 1 if self.is_horizontal() else 0
+ for segment in segments:
+ segment[0, pos] = lineoffset + linelength / 2.
+ segment[1, pos] = lineoffset - linelength / 2.
+ self.set_segments(segments)
+ self._linelength = linelength
+
+ def get_lineoffset(self):
+ """Return the offset of the lines used to mark each event."""
+ return self._lineoffset
+
+ def set_lineoffset(self, lineoffset):
+ """Set the offset of the lines used to mark each event."""
+ if lineoffset == self.get_lineoffset():
+ return
+ linelength = self.get_linelength()
+ segments = self.get_segments()
+ pos = 1 if self.is_horizontal() else 0
+ for segment in segments:
+ segment[0, pos] = lineoffset + linelength / 2.
+ segment[1, pos] = lineoffset - linelength / 2.
+ self.set_segments(segments)
+ self._lineoffset = lineoffset
+
+ def get_linewidth(self):
+ """Get the width of the lines used to mark each event."""
+ return super().get_linewidth()[0]
+
+ def get_linewidths(self):
+ return super().get_linewidth()
+
+ def get_color(self):
+ """Return the color of the lines used to mark each event."""
+ return self.get_colors()[0]
+
+
+class CircleCollection(_CollectionWithSizes):
+ """A collection of circles, drawn using splines."""
+
+ _factor = np.pi ** (-1/2)
+
+ def __init__(self, sizes, **kwargs):
+ """
+ Parameters
+ ----------
+ sizes : float or array-like
+ The area of each circle in points^2.
+ **kwargs
+ Forwarded to `.Collection`.
+ """
+ super().__init__(**kwargs)
+ self.set_sizes(sizes)
+ self.set_transform(transforms.IdentityTransform())
+ self._paths = [mpath.Path.unit_circle()]
+
+
+class EllipseCollection(Collection):
+ """A collection of ellipses, drawn using splines."""
+
+ def __init__(self, widths, heights, angles, *, units='points', **kwargs):
+ """
+ Parameters
+ ----------
+ widths : array-like
+ The lengths of the first axes (e.g., major axis lengths).
+ heights : array-like
+ The lengths of second axes.
+ angles : array-like
+ The angles of the first axes, degrees CCW from the x-axis.
+ units : {'points', 'inches', 'dots', 'width', 'height', 'x', 'y', 'xy'}
+ The units in which majors and minors are given; 'width' and
+ 'height' refer to the dimensions of the axes, while 'x' and 'y'
+ refer to the *offsets* data units. 'xy' differs from all others in
+ that the angle as plotted varies with the aspect ratio, and equals
+ the specified angle only when the aspect ratio is unity. Hence
+ it behaves the same as the `~.patches.Ellipse` with
+ ``axes.transData`` as its transform.
+ **kwargs
+ Forwarded to `Collection`.
+ """
+ super().__init__(**kwargs)
+ self.set_widths(widths)
+ self.set_heights(heights)
+ self.set_angles(angles)
+ self._units = units
+ self.set_transform(transforms.IdentityTransform())
+ self._transforms = np.empty((0, 3, 3))
+ self._paths = [mpath.Path.unit_circle()]
+
+ def _set_transforms(self):
+ """Calculate transforms immediately before drawing."""
+
+ ax = self.axes
+ fig = self.get_figure(root=False)
+
+ if self._units == 'xy':
+ sc = 1
+ elif self._units == 'x':
+ sc = ax.bbox.width / ax.viewLim.width
+ elif self._units == 'y':
+ sc = ax.bbox.height / ax.viewLim.height
+ elif self._units == 'inches':
+ sc = fig.dpi
+ elif self._units == 'points':
+ sc = fig.dpi / 72.0
+ elif self._units == 'width':
+ sc = ax.bbox.width
+ elif self._units == 'height':
+ sc = ax.bbox.height
+ elif self._units == 'dots':
+ sc = 1.0
+ else:
+ raise ValueError(f'Unrecognized units: {self._units!r}')
+
+ self._transforms = np.zeros((len(self._widths), 3, 3))
+ widths = self._widths * sc
+ heights = self._heights * sc
+ sin_angle = np.sin(self._angles)
+ cos_angle = np.cos(self._angles)
+ self._transforms[:, 0, 0] = widths * cos_angle
+ self._transforms[:, 0, 1] = heights * -sin_angle
+ self._transforms[:, 1, 0] = widths * sin_angle
+ self._transforms[:, 1, 1] = heights * cos_angle
+ self._transforms[:, 2, 2] = 1.0
+
+ _affine = transforms.Affine2D
+ if self._units == 'xy':
+ m = ax.transData.get_affine().get_matrix().copy()
+ m[:2, 2:] = 0
+ self.set_transform(_affine(m))
+
+ def set_widths(self, widths):
+ """Set the lengths of the first axes (e.g., major axis)."""
+ self._widths = 0.5 * np.asarray(widths).ravel()
+ self.stale = True
+
+ def set_heights(self, heights):
+ """Set the lengths of second axes (e.g., minor axes)."""
+ self._heights = 0.5 * np.asarray(heights).ravel()
+ self.stale = True
+
+ def set_angles(self, angles):
+ """Set the angles of the first axes, degrees CCW from the x-axis."""
+ self._angles = np.deg2rad(angles).ravel()
+ self.stale = True
+
+ def get_widths(self):
+ """Get the lengths of the first axes (e.g., major axis)."""
+ return self._widths * 2
+
+ def get_heights(self):
+ """Set the lengths of second axes (e.g., minor axes)."""
+ return self._heights * 2
+
+ def get_angles(self):
+ """Get the angles of the first axes, degrees CCW from the x-axis."""
+ return np.rad2deg(self._angles)
+
+ @artist.allow_rasterization
+ def draw(self, renderer):
+ self._set_transforms()
+ super().draw(renderer)
+
+
+class PatchCollection(Collection):
+ """
+ A generic collection of patches.
+
+ PatchCollection draws faster than a large number of equivalent individual
+ Patches. It also makes it easier to assign a colormap to a heterogeneous
+ collection of patches.
+ """
+
+ def __init__(self, patches, *, match_original=False, **kwargs):
+ """
+ Parameters
+ ----------
+ patches : list of `.Patch`
+ A sequence of Patch objects. This list may include
+ a heterogeneous assortment of different patch types.
+
+ match_original : bool, default: False
+ If True, use the colors and linewidths of the original
+ patches. If False, new colors may be assigned by
+ providing the standard collection arguments, facecolor,
+ edgecolor, linewidths, norm or cmap.
+
+ **kwargs
+ All other parameters are forwarded to `.Collection`.
+
+ If any of *edgecolors*, *facecolors*, *linewidths*, *antialiaseds*
+ are None, they default to their `.rcParams` patch setting, in
+ sequence form.
+
+ Notes
+ -----
+ The use of `~matplotlib.cm.ScalarMappable` functionality is optional.
+ If the `~matplotlib.cm.ScalarMappable` matrix ``_A`` has been set (via
+ a call to `~.ScalarMappable.set_array`), at draw time a call to scalar
+ mappable will be made to set the face colors.
+ """
+
+ if match_original:
+ def determine_facecolor(patch):
+ if patch.get_fill():
+ return patch.get_facecolor()
+ return [0, 0, 0, 0]
+
+ kwargs['facecolors'] = [determine_facecolor(p) for p in patches]
+ kwargs['edgecolors'] = [p.get_edgecolor() for p in patches]
+ kwargs['linewidths'] = [p.get_linewidth() for p in patches]
+ kwargs['linestyles'] = [p.get_linestyle() for p in patches]
+ kwargs['antialiaseds'] = [p.get_antialiased() for p in patches]
+
+ super().__init__(**kwargs)
+
+ self.set_paths(patches)
+
+ def set_paths(self, patches):
+ paths = [p.get_transform().transform_path(p.get_path())
+ for p in patches]
+ self._paths = paths
+
+
+class TriMesh(Collection):
+ """
+ Class for the efficient drawing of a triangular mesh using Gouraud shading.
+
+ A triangular mesh is a `~matplotlib.tri.Triangulation` object.
+ """
+ def __init__(self, triangulation, **kwargs):
+ super().__init__(**kwargs)
+ self._triangulation = triangulation
+ self._shading = 'gouraud'
+
+ self._bbox = transforms.Bbox.unit()
+
+ # Unfortunately this requires a copy, unless Triangulation
+ # was rewritten.
+ xy = np.hstack((triangulation.x.reshape(-1, 1),
+ triangulation.y.reshape(-1, 1)))
+ self._bbox.update_from_data_xy(xy)
+
+ def get_paths(self):
+ if self._paths is None:
+ self.set_paths()
+ return self._paths
+
+ def set_paths(self):
+ self._paths = self.convert_mesh_to_paths(self._triangulation)
+
+ @staticmethod
+ def convert_mesh_to_paths(tri):
+ """
+ Convert a given mesh into a sequence of `.Path` objects.
+
+ This function is primarily of use to implementers of backends that do
+ not directly support meshes.
+ """
+ triangles = tri.get_masked_triangles()
+ verts = np.stack((tri.x[triangles], tri.y[triangles]), axis=-1)
+ return [mpath.Path(x) for x in verts]
+
+ @artist.allow_rasterization
+ def draw(self, renderer):
+ if not self.get_visible():
+ return
+ renderer.open_group(self.__class__.__name__, gid=self.get_gid())
+ transform = self.get_transform()
+
+ # Get a list of triangles and the color at each vertex.
+ tri = self._triangulation
+ triangles = tri.get_masked_triangles()
+
+ verts = np.stack((tri.x[triangles], tri.y[triangles]), axis=-1)
+
+ self.update_scalarmappable()
+ colors = self._facecolors[triangles]
+
+ gc = renderer.new_gc()
+ self._set_gc_clip(gc)
+ gc.set_linewidth(self.get_linewidth()[0])
+ renderer.draw_gouraud_triangles(gc, verts, colors, transform.frozen())
+ gc.restore()
+ renderer.close_group(self.__class__.__name__)
+
+
+class _MeshData:
+ r"""
+ Class for managing the two dimensional coordinates of Quadrilateral meshes
+ and the associated data with them. This class is a mixin and is intended to
+ be used with another collection that will implement the draw separately.
+
+ A quadrilateral mesh is a grid of M by N adjacent quadrilaterals that are
+ defined via a (M+1, N+1) grid of vertices. The quadrilateral (m, n) is
+ defined by the vertices ::
+
+ (m+1, n) ----------- (m+1, n+1)
+ / /
+ / /
+ / /
+ (m, n) -------- (m, n+1)
+
+ The mesh need not be regular and the polygons need not be convex.
+
+ Parameters
+ ----------
+ coordinates : (M+1, N+1, 2) array-like
+ The vertices. ``coordinates[m, n]`` specifies the (x, y) coordinates
+ of vertex (m, n).
+
+ shading : {'flat', 'gouraud'}, default: 'flat'
+ """
+ def __init__(self, coordinates, *, shading='flat'):
+ _api.check_shape((None, None, 2), coordinates=coordinates)
+ self._coordinates = coordinates
+ self._shading = shading
+
+ def set_array(self, A):
+ """
+ Set the data values.
+
+ Parameters
+ ----------
+ A : array-like
+ The mesh data. Supported array shapes are:
+
+ - (M, N) or (M*N,): a mesh with scalar data. The values are mapped
+ to colors using normalization and a colormap. See parameters
+ *norm*, *cmap*, *vmin*, *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.
+
+ If the values are provided as a 2D grid, the shape must match the
+ coordinates grid. If the values are 1D, they are reshaped to 2D.
+ M, N follow from the coordinates grid, where the coordinates grid
+ shape is (M, N) for 'gouraud' *shading* and (M+1, N+1) for 'flat'
+ shading.
+ """
+ height, width = self._coordinates.shape[0:-1]
+ if self._shading == 'flat':
+ h, w = height - 1, width - 1
+ else:
+ h, w = height, width
+ ok_shapes = [(h, w, 3), (h, w, 4), (h, w), (h * w,)]
+ if A is not None:
+ shape = np.shape(A)
+ if shape not in ok_shapes:
+ raise ValueError(
+ f"For X ({width}) and Y ({height}) with {self._shading} "
+ f"shading, A should have shape "
+ f"{' or '.join(map(str, ok_shapes))}, not {A.shape}")
+ return super().set_array(A)
+
+ def get_coordinates(self):
+ """
+ Return the vertices of the mesh as an (M+1, N+1, 2) array.
+
+ M, N are the number of quadrilaterals in the rows / columns of the
+ mesh, corresponding to (M+1, N+1) vertices.
+ The last dimension specifies the components (x, y).
+ """
+ return self._coordinates
+
+ def get_edgecolor(self):
+ # docstring inherited
+ # Note that we want to return an array of shape (N*M, 4)
+ # a flattened RGBA collection
+ return super().get_edgecolor().reshape(-1, 4)
+
+ def get_facecolor(self):
+ # docstring inherited
+ # Note that we want to return an array of shape (N*M, 4)
+ # a flattened RGBA collection
+ return super().get_facecolor().reshape(-1, 4)
+
+ @staticmethod
+ def _convert_mesh_to_paths(coordinates):
+ """
+ Convert a given mesh into a sequence of `.Path` objects.
+
+ This function is primarily of use to implementers of backends that do
+ not directly support quadmeshes.
+ """
+ if isinstance(coordinates, np.ma.MaskedArray):
+ c = coordinates.data
+ else:
+ c = coordinates
+ points = np.concatenate([
+ c[:-1, :-1],
+ c[:-1, 1:],
+ c[1:, 1:],
+ c[1:, :-1],
+ c[:-1, :-1]
+ ], axis=2).reshape((-1, 5, 2))
+ return [mpath.Path(x) for x in points]
+
+ def _convert_mesh_to_triangles(self, coordinates):
+ """
+ Convert a given mesh into a sequence of triangles, each point
+ with its own color. The result can be used to construct a call to
+ `~.RendererBase.draw_gouraud_triangles`.
+ """
+ if isinstance(coordinates, np.ma.MaskedArray):
+ p = coordinates.data
+ else:
+ p = coordinates
+
+ p_a = p[:-1, :-1]
+ p_b = p[:-1, 1:]
+ p_c = p[1:, 1:]
+ p_d = p[1:, :-1]
+ p_center = (p_a + p_b + p_c + p_d) / 4.0
+ triangles = np.concatenate([
+ p_a, p_b, p_center,
+ p_b, p_c, p_center,
+ p_c, p_d, p_center,
+ p_d, p_a, p_center,
+ ], axis=2).reshape((-1, 3, 2))
+
+ c = self.get_facecolor().reshape((*coordinates.shape[:2], 4))
+ z = self.get_array()
+ mask = z.mask if np.ma.is_masked(z) else None
+ if mask is not None:
+ c[mask, 3] = np.nan
+ c_a = c[:-1, :-1]
+ c_b = c[:-1, 1:]
+ c_c = c[1:, 1:]
+ c_d = c[1:, :-1]
+ c_center = (c_a + c_b + c_c + c_d) / 4.0
+ colors = np.concatenate([
+ c_a, c_b, c_center,
+ c_b, c_c, c_center,
+ c_c, c_d, c_center,
+ c_d, c_a, c_center,
+ ], axis=2).reshape((-1, 3, 4))
+ tmask = np.isnan(colors[..., 2, 3])
+ return triangles[~tmask], colors[~tmask]
+
+
+class QuadMesh(_MeshData, Collection):
+ r"""
+ Class for the efficient drawing of a quadrilateral mesh.
+
+ A quadrilateral mesh is a grid of M by N adjacent quadrilaterals that are
+ defined via a (M+1, N+1) grid of vertices. The quadrilateral (m, n) is
+ defined by the vertices ::
+
+ (m+1, n) ----------- (m+1, n+1)
+ / /
+ / /
+ / /
+ (m, n) -------- (m, n+1)
+
+ The mesh need not be regular and the polygons need not be convex.
+
+ Parameters
+ ----------
+ coordinates : (M+1, N+1, 2) array-like
+ The vertices. ``coordinates[m, n]`` specifies the (x, y) coordinates
+ of vertex (m, n).
+
+ antialiased : bool, default: True
+
+ shading : {'flat', 'gouraud'}, default: 'flat'
+
+ Notes
+ -----
+ Unlike other `.Collection`\s, the default *pickradius* of `.QuadMesh` is 0,
+ i.e. `~.Artist.contains` checks whether the test point is within any of the
+ mesh quadrilaterals.
+
+ """
+
+ def __init__(self, coordinates, *, antialiased=True, shading='flat',
+ **kwargs):
+ kwargs.setdefault("pickradius", 0)
+ super().__init__(coordinates=coordinates, shading=shading)
+ Collection.__init__(self, **kwargs)
+
+ self._antialiased = antialiased
+ self._bbox = transforms.Bbox.unit()
+ self._bbox.update_from_data_xy(self._coordinates.reshape(-1, 2))
+ self.set_mouseover(False)
+
+ def get_paths(self):
+ if self._paths is None:
+ self.set_paths()
+ return self._paths
+
+ def set_paths(self):
+ self._paths = self._convert_mesh_to_paths(self._coordinates)
+ self.stale = True
+
+ def get_datalim(self, transData):
+ return (self.get_transform() - transData).transform_bbox(self._bbox)
+
+ @artist.allow_rasterization
+ def draw(self, renderer):
+ if not self.get_visible():
+ return
+ renderer.open_group(self.__class__.__name__, self.get_gid())
+ transform = self.get_transform()
+ offset_trf = self.get_offset_transform()
+ offsets = self.get_offsets()
+
+ if self.have_units():
+ xs = self.convert_xunits(offsets[:, 0])
+ ys = self.convert_yunits(offsets[:, 1])
+ offsets = np.column_stack([xs, ys])
+
+ self.update_scalarmappable()
+
+ if not transform.is_affine:
+ coordinates = self._coordinates.reshape((-1, 2))
+ coordinates = transform.transform(coordinates)
+ coordinates = coordinates.reshape(self._coordinates.shape)
+ transform = transforms.IdentityTransform()
+ else:
+ coordinates = self._coordinates
+
+ if not offset_trf.is_affine:
+ offsets = offset_trf.transform_non_affine(offsets)
+ offset_trf = offset_trf.get_affine()
+
+ gc = renderer.new_gc()
+ gc.set_snap(self.get_snap())
+ self._set_gc_clip(gc)
+ gc.set_linewidth(self.get_linewidth()[0])
+
+ if self._shading == 'gouraud':
+ triangles, colors = self._convert_mesh_to_triangles(coordinates)
+ renderer.draw_gouraud_triangles(
+ gc, triangles, colors, transform.frozen())
+ else:
+ renderer.draw_quad_mesh(
+ gc, transform.frozen(),
+ coordinates.shape[1] - 1, coordinates.shape[0] - 1,
+ coordinates, offsets, offset_trf,
+ # Backends expect flattened rgba arrays (n*m, 4) for fc and ec
+ self.get_facecolor().reshape((-1, 4)),
+ self._antialiased, self.get_edgecolors().reshape((-1, 4)))
+ gc.restore()
+ renderer.close_group(self.__class__.__name__)
+ self.stale = False
+
+ def get_cursor_data(self, event):
+ contained, info = self.contains(event)
+ if contained and self.get_array() is not None:
+ return self.get_array().ravel()[info["ind"]]
+ return None
+
+
+class PolyQuadMesh(_MeshData, PolyCollection):
+ """
+ Class for drawing a quadrilateral mesh as individual Polygons.
+
+ A quadrilateral mesh is a grid of M by N adjacent quadrilaterals that are
+ defined via a (M+1, N+1) grid of vertices. The quadrilateral (m, n) is
+ defined by the vertices ::
+
+ (m+1, n) ----------- (m+1, n+1)
+ / /
+ / /
+ / /
+ (m, n) -------- (m, n+1)
+
+ The mesh need not be regular and the polygons need not be convex.
+
+ Parameters
+ ----------
+ coordinates : (M+1, N+1, 2) array-like
+ The vertices. ``coordinates[m, n]`` specifies the (x, y) coordinates
+ of vertex (m, n).
+
+ Notes
+ -----
+ Unlike `.QuadMesh`, this class will draw each cell as an individual Polygon.
+ This is significantly slower, but allows for more flexibility when wanting
+ to add additional properties to the cells, such as hatching.
+
+ Another difference from `.QuadMesh` is that if any of the vertices or data
+ of a cell are masked, that Polygon will **not** be drawn and it won't be in
+ the list of paths returned.
+ """
+
+ def __init__(self, coordinates, **kwargs):
+ super().__init__(coordinates=coordinates)
+ PolyCollection.__init__(self, verts=[], **kwargs)
+ # Setting the verts updates the paths of the PolyCollection
+ # This is called after the initializers to make sure the kwargs
+ # have all been processed and available for the masking calculations
+ self._set_unmasked_verts()
+
+ def _get_unmasked_polys(self):
+ """Get the unmasked regions using the coordinates and array"""
+ # mask(X) | mask(Y)
+ mask = np.any(np.ma.getmaskarray(self._coordinates), axis=-1)
+
+ # We want the shape of the polygon, which is the corner of each X/Y array
+ mask = (mask[0:-1, 0:-1] | mask[1:, 1:] | mask[0:-1, 1:] | mask[1:, 0:-1])
+ arr = self.get_array()
+ if arr is not None:
+ arr = np.ma.getmaskarray(arr)
+ if arr.ndim == 3:
+ # RGB(A) case
+ mask |= np.any(arr, axis=-1)
+ elif arr.ndim == 2:
+ mask |= arr
+ else:
+ mask |= arr.reshape(self._coordinates[:-1, :-1, :].shape[:2])
+ return ~mask
+
+ def _set_unmasked_verts(self):
+ X = self._coordinates[..., 0]
+ Y = self._coordinates[..., 1]
+
+ unmask = self._get_unmasked_polys()
+ X1 = np.ma.filled(X[:-1, :-1])[unmask]
+ Y1 = np.ma.filled(Y[:-1, :-1])[unmask]
+ X2 = np.ma.filled(X[1:, :-1])[unmask]
+ Y2 = np.ma.filled(Y[1:, :-1])[unmask]
+ X3 = np.ma.filled(X[1:, 1:])[unmask]
+ Y3 = np.ma.filled(Y[1:, 1:])[unmask]
+ X4 = np.ma.filled(X[:-1, 1:])[unmask]
+ Y4 = np.ma.filled(Y[:-1, 1:])[unmask]
+ npoly = len(X1)
+
+ xy = np.ma.stack([X1, Y1, X2, Y2, X3, Y3, X4, Y4, X1, Y1], axis=-1)
+ verts = xy.reshape((npoly, 5, 2))
+ self.set_verts(verts)
+
+ def get_edgecolor(self):
+ # docstring inherited
+ # We only want to return the facecolors of the polygons
+ # that were drawn.
+ ec = super().get_edgecolor()
+ unmasked_polys = self._get_unmasked_polys().ravel()
+ if len(ec) != len(unmasked_polys):
+ # Mapping is off
+ return ec
+ return ec[unmasked_polys, :]
+
+ def get_facecolor(self):
+ # docstring inherited
+ # We only want to return the facecolors of the polygons
+ # that were drawn.
+ fc = super().get_facecolor()
+ unmasked_polys = self._get_unmasked_polys().ravel()
+ if len(fc) != len(unmasked_polys):
+ # Mapping is off
+ return fc
+ return fc[unmasked_polys, :]
+
+ def set_array(self, A):
+ # docstring inherited
+ prev_unmask = self._get_unmasked_polys()
+ super().set_array(A)
+ # If the mask has changed at all we need to update
+ # the set of Polys that we are drawing
+ if not np.array_equal(prev_unmask, self._get_unmasked_polys()):
+ self._set_unmasked_verts()
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/collections.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/collections.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..0805adef42935aad06d51d3f3ed093923c02c16b
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/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/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/colorbar.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/colorbar.py
new file mode 100644
index 0000000000000000000000000000000000000000..1cf3b77f01c230d5c49db68de5e9c85fd3f29a32
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/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:
+ a._colorbars.append(cax) # tell the parent it has a colorbar
+ 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="")
+ parent._colorbars.append(cax) # tell the parent it has a colorbar
+ 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/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/colorbar.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/colorbar.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..07467ca74f3d5a528f8c1c0859fc25a2eb285664
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/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/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/colorizer.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/colorizer.py
new file mode 100644
index 0000000000000000000000000000000000000000..b4223f38980410c1929d598265cd3dab1c3cfcad
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/colorizer.py
@@ -0,0 +1,703 @@
+"""
+The Colorizer class which handles the data to color pipeline via a
+normalization and a colormap.
+
+.. admonition:: Provisional status of colorizer
+
+ The ``colorizer`` module and classes in this file are considered
+ provisional and may change at any time without a deprecation period.
+
+.. seealso::
+
+ :doc:`/gallery/color/colormap_reference` for a list of builtin colormaps.
+
+ :ref:`colormap-manipulation` for examples of how to make colormaps.
+
+ :ref:`colormaps` for an in-depth discussion of choosing colormaps.
+
+ :ref:`colormapnorms` for more details about data normalization.
+
+"""
+
+import functools
+
+import numpy as np
+from numpy import ma
+
+from matplotlib import _api, colors, cbook, scale, artist
+import matplotlib as mpl
+
+mpl._docstring.interpd.register(
+ colorizer_doc="""\
+colorizer : `~matplotlib.colorizer.Colorizer` or None, default: None
+ The Colorizer object used to map color to data. If None, a Colorizer
+ object is created from a *norm* and *cmap*.""",
+ )
+
+
+class Colorizer:
+ """
+ Data to color pipeline.
+
+ This pipeline is accessible via `.Colorizer.to_rgba` and executed via
+ the `.Colorizer.norm` and `.Colorizer.cmap` attributes.
+
+ Parameters
+ ----------
+ cmap: colorbar.Colorbar or str or None, default: None
+ The colormap used to color data.
+
+ norm: colors.Normalize or str or None, default: None
+ The normalization used to normalize the data
+ """
+ def __init__(self, cmap=None, norm=None):
+
+ self._cmap = None
+ self._set_cmap(cmap)
+
+ self._id_norm = None
+ self._norm = None
+ self.norm = norm
+
+ self.callbacks = cbook.CallbackRegistry(signals=["changed"])
+ self.colorbar = None
+
+ def _scale_norm(self, norm, vmin, vmax, A):
+ """
+ Helper for initial scaling.
+
+ Used by public functions that create a ScalarMappable and support
+ parameters *vmin*, *vmax* and *norm*. This makes sure that a *norm*
+ will take precedence over *vmin*, *vmax*.
+
+ Note that this method does not set the norm.
+ """
+ if vmin is not None or vmax is not None:
+ self.set_clim(vmin, vmax)
+ if isinstance(norm, colors.Normalize):
+ raise ValueError(
+ "Passing a Normalize instance simultaneously with "
+ "vmin/vmax is not supported. Please pass vmin/vmax "
+ "directly to the norm when creating it.")
+
+ # always resolve the autoscaling so we have concrete limits
+ # rather than deferring to draw time.
+ self.autoscale_None(A)
+
+ @property
+ def norm(self):
+ return self._norm
+
+ @norm.setter
+ def norm(self, norm):
+ _api.check_isinstance((colors.Normalize, str, None), norm=norm)
+ if norm is None:
+ norm = colors.Normalize()
+ elif isinstance(norm, str):
+ try:
+ scale_cls = scale._scale_mapping[norm]
+ except KeyError:
+ raise ValueError(
+ "Invalid norm str name; the following values are "
+ f"supported: {', '.join(scale._scale_mapping)}"
+ ) from None
+ norm = _auto_norm_from_scale(scale_cls)()
+
+ if norm is self.norm:
+ # We aren't updating anything
+ return
+
+ in_init = self.norm is None
+ # Remove the current callback and connect to the new one
+ if not in_init:
+ self.norm.callbacks.disconnect(self._id_norm)
+ self._norm = norm
+ self._id_norm = self.norm.callbacks.connect('changed',
+ self.changed)
+ if not in_init:
+ self.changed()
+
+ def to_rgba(self, x, alpha=None, bytes=False, norm=True):
+ """
+ Return a normalized RGBA array corresponding to *x*.
+
+ In the normal case, *x* is a 1D or 2D sequence of scalars, and
+ the corresponding `~numpy.ndarray` of RGBA values will be returned,
+ based on the norm and colormap set for this Colorizer.
+
+ There is one special case, for handling images that are already
+ RGB or RGBA, such as might have been read from an image file.
+ If *x* is an `~numpy.ndarray` with 3 dimensions,
+ and the last dimension is either 3 or 4, then it will be
+ treated as an RGB or RGBA array, and no mapping will be done.
+ The array can be `~numpy.uint8`, or it can be floats with
+ values in the 0-1 range; otherwise a ValueError will be raised.
+ Any NaNs or masked elements will be set to 0 alpha.
+ If the last dimension is 3, the *alpha* kwarg (defaulting to 1)
+ will be used to fill in the transparency. If the last dimension
+ is 4, the *alpha* kwarg is ignored; it does not
+ replace the preexisting alpha. A ValueError will be raised
+ if the third dimension is other than 3 or 4.
+
+ In either case, if *bytes* is *False* (default), the RGBA
+ array will be floats in the 0-1 range; if it is *True*,
+ the returned RGBA array will be `~numpy.uint8` in the 0 to 255 range.
+
+ If norm is False, no normalization of the input data is
+ performed, and it is assumed to be in the range (0-1).
+
+ """
+ # First check for special case, image input:
+ if isinstance(x, np.ndarray) and x.ndim == 3:
+ return self._pass_image_data(x, alpha, bytes, norm)
+
+ # Otherwise run norm -> colormap pipeline
+ x = ma.asarray(x)
+ if norm:
+ x = self.norm(x)
+ rgba = self.cmap(x, alpha=alpha, bytes=bytes)
+ return rgba
+
+ @staticmethod
+ def _pass_image_data(x, alpha=None, bytes=False, norm=True):
+ """
+ Helper function to pass ndarray of shape (...,3) or (..., 4)
+ through `to_rgba()`, see `to_rgba()` for docstring.
+ """
+ if x.shape[2] == 3:
+ if alpha is None:
+ alpha = 1
+ if x.dtype == np.uint8:
+ alpha = np.uint8(alpha * 255)
+ m, n = x.shape[:2]
+ xx = np.empty(shape=(m, n, 4), dtype=x.dtype)
+ xx[:, :, :3] = x
+ xx[:, :, 3] = alpha
+ elif x.shape[2] == 4:
+ xx = x
+ else:
+ raise ValueError("Third dimension must be 3 or 4")
+ if xx.dtype.kind == 'f':
+ # If any of R, G, B, or A is nan, set to 0
+ if np.any(nans := np.isnan(x)):
+ if x.shape[2] == 4:
+ xx = xx.copy()
+ xx[np.any(nans, axis=2), :] = 0
+
+ if norm and (xx.max() > 1 or xx.min() < 0):
+ raise ValueError("Floating point image RGB values "
+ "must be in the 0..1 range.")
+ if bytes:
+ xx = (xx * 255).astype(np.uint8)
+ elif xx.dtype == np.uint8:
+ if not bytes:
+ xx = xx.astype(np.float32) / 255
+ else:
+ raise ValueError("Image RGB array must be uint8 or "
+ "floating point; found %s" % xx.dtype)
+ # Account for any masked entries in the original array
+ # If any of R, G, B, or A are masked for an entry, we set alpha to 0
+ if np.ma.is_masked(x):
+ xx[np.any(np.ma.getmaskarray(x), axis=2), 3] = 0
+ return xx
+
+ def autoscale(self, A):
+ """
+ Autoscale the scalar limits on the norm instance using the
+ current array
+ """
+ if A is None:
+ raise TypeError('You must first set_array for mappable')
+ # If the norm's limits are updated self.changed() will be called
+ # through the callbacks attached to the norm
+ self.norm.autoscale(A)
+
+ def autoscale_None(self, A):
+ """
+ Autoscale the scalar limits on the norm instance using the
+ current array, changing only limits that are None
+ """
+ if A is None:
+ raise TypeError('You must first set_array for mappable')
+ # If the norm's limits are updated self.changed() will be called
+ # through the callbacks attached to the norm
+ self.norm.autoscale_None(A)
+
+ def _set_cmap(self, cmap):
+ """
+ Set the colormap for luminance data.
+
+ Parameters
+ ----------
+ cmap : `.Colormap` or str or None
+ """
+ # bury import to avoid circular imports
+ from matplotlib import cm
+ in_init = self._cmap is None
+ self._cmap = cm._ensure_cmap(cmap)
+ if not in_init:
+ self.changed() # Things are not set up properly yet.
+
+ @property
+ def cmap(self):
+ return self._cmap
+
+ @cmap.setter
+ def cmap(self, cmap):
+ self._set_cmap(cmap)
+
+ def set_clim(self, vmin=None, vmax=None):
+ """
+ Set the norm limits for image scaling.
+
+ Parameters
+ ----------
+ vmin, vmax : float
+ The limits.
+
+ The limits may also be passed as a tuple (*vmin*, *vmax*) as a
+ single positional argument.
+
+ .. ACCEPTS: (vmin: float, vmax: float)
+ """
+ # If the norm's limits are updated self.changed() will be called
+ # through the callbacks attached to the norm, this causes an inconsistent
+ # state, to prevent this blocked context manager is used
+ if vmax is None:
+ try:
+ vmin, vmax = vmin
+ except (TypeError, ValueError):
+ pass
+
+ orig_vmin_vmax = self.norm.vmin, self.norm.vmax
+
+ # Blocked context manager prevents callbacks from being triggered
+ # until both vmin and vmax are updated
+ with self.norm.callbacks.blocked(signal='changed'):
+ if vmin is not None:
+ self.norm.vmin = colors._sanitize_extrema(vmin)
+ if vmax is not None:
+ self.norm.vmax = colors._sanitize_extrema(vmax)
+
+ # emit a update signal if the limits are changed
+ if orig_vmin_vmax != (self.norm.vmin, self.norm.vmax):
+ self.norm.callbacks.process('changed')
+
+ def get_clim(self):
+ """
+ Return the values (min, max) that are mapped to the colormap limits.
+ """
+ return self.norm.vmin, self.norm.vmax
+
+ def changed(self):
+ """
+ Call this whenever the mappable is changed to notify all the
+ callbackSM listeners to the 'changed' signal.
+ """
+ self.callbacks.process('changed')
+ self.stale = True
+
+ @property
+ def vmin(self):
+ return self.get_clim()[0]
+
+ @vmin.setter
+ def vmin(self, vmin):
+ self.set_clim(vmin=vmin)
+
+ @property
+ def vmax(self):
+ return self.get_clim()[1]
+
+ @vmax.setter
+ def vmax(self, vmax):
+ self.set_clim(vmax=vmax)
+
+ @property
+ def clip(self):
+ return self.norm.clip
+
+ @clip.setter
+ def clip(self, clip):
+ self.norm.clip = clip
+
+
+class _ColorizerInterface:
+ """
+ Base class that contains the interface to `Colorizer` objects from
+ a `ColorizingArtist` or `.cm.ScalarMappable`.
+
+ Note: This class only contain functions that interface the .colorizer
+ attribute. Other functions that as shared between `.ColorizingArtist`
+ and `.cm.ScalarMappable` are not included.
+ """
+ def _scale_norm(self, norm, vmin, vmax):
+ self._colorizer._scale_norm(norm, vmin, vmax, self._A)
+
+ def to_rgba(self, x, alpha=None, bytes=False, norm=True):
+ """
+ Return a normalized RGBA array corresponding to *x*.
+
+ In the normal case, *x* is a 1D or 2D sequence of scalars, and
+ the corresponding `~numpy.ndarray` of RGBA values will be returned,
+ based on the norm and colormap set for this Colorizer.
+
+ There is one special case, for handling images that are already
+ RGB or RGBA, such as might have been read from an image file.
+ If *x* is an `~numpy.ndarray` with 3 dimensions,
+ and the last dimension is either 3 or 4, then it will be
+ treated as an RGB or RGBA array, and no mapping will be done.
+ The array can be `~numpy.uint8`, or it can be floats with
+ values in the 0-1 range; otherwise a ValueError will be raised.
+ Any NaNs or masked elements will be set to 0 alpha.
+ If the last dimension is 3, the *alpha* kwarg (defaulting to 1)
+ will be used to fill in the transparency. If the last dimension
+ is 4, the *alpha* kwarg is ignored; it does not
+ replace the preexisting alpha. A ValueError will be raised
+ if the third dimension is other than 3 or 4.
+
+ In either case, if *bytes* is *False* (default), the RGBA
+ array will be floats in the 0-1 range; if it is *True*,
+ the returned RGBA array will be `~numpy.uint8` in the 0 to 255 range.
+
+ If norm is False, no normalization of the input data is
+ performed, and it is assumed to be in the range (0-1).
+
+ """
+ return self._colorizer.to_rgba(x, alpha=alpha, bytes=bytes, norm=norm)
+
+ def get_clim(self):
+ """
+ Return the values (min, max) that are mapped to the colormap limits.
+ """
+ return self._colorizer.get_clim()
+
+ def set_clim(self, vmin=None, vmax=None):
+ """
+ Set the norm limits for image scaling.
+
+ Parameters
+ ----------
+ vmin, vmax : float
+ The limits.
+
+ For scalar data, the limits may also be passed as a
+ tuple (*vmin*, *vmax*) as a single positional argument.
+
+ .. ACCEPTS: (vmin: float, vmax: float)
+ """
+ # If the norm's limits are updated self.changed() will be called
+ # through the callbacks attached to the norm
+ self._colorizer.set_clim(vmin, vmax)
+
+ def get_alpha(self):
+ try:
+ return super().get_alpha()
+ except AttributeError:
+ return 1
+
+ @property
+ def cmap(self):
+ return self._colorizer.cmap
+
+ @cmap.setter
+ def cmap(self, cmap):
+ self._colorizer.cmap = cmap
+
+ def get_cmap(self):
+ """Return the `.Colormap` instance."""
+ return self._colorizer.cmap
+
+ def set_cmap(self, cmap):
+ """
+ Set the colormap for luminance data.
+
+ Parameters
+ ----------
+ cmap : `.Colormap` or str or None
+ """
+ self.cmap = cmap
+
+ @property
+ def norm(self):
+ return self._colorizer.norm
+
+ @norm.setter
+ def norm(self, norm):
+ self._colorizer.norm = norm
+
+ def set_norm(self, norm):
+ """
+ Set the normalization instance.
+
+ Parameters
+ ----------
+ norm : `.Normalize` or str or None
+
+ Notes
+ -----
+ If there are any colorbars using the mappable for this norm, setting
+ the norm of the mappable will reset the norm, locator, and formatters
+ on the colorbar to default.
+ """
+ self.norm = norm
+
+ def autoscale(self):
+ """
+ Autoscale the scalar limits on the norm instance using the
+ current array
+ """
+ self._colorizer.autoscale(self._A)
+
+ def autoscale_None(self):
+ """
+ Autoscale the scalar limits on the norm instance using the
+ current array, changing only limits that are None
+ """
+ self._colorizer.autoscale_None(self._A)
+
+ @property
+ def colorbar(self):
+ """
+ The last colorbar associated with this object. May be None
+ """
+ return self._colorizer.colorbar
+
+ @colorbar.setter
+ def colorbar(self, colorbar):
+ self._colorizer.colorbar = colorbar
+
+ def _format_cursor_data_override(self, data):
+ # This function overwrites Artist.format_cursor_data(). We cannot
+ # implement cm.ScalarMappable.format_cursor_data() directly, because
+ # most cm.ScalarMappable subclasses inherit from Artist first and from
+ # cm.ScalarMappable second, so Artist.format_cursor_data would always
+ # have precedence over cm.ScalarMappable.format_cursor_data.
+
+ # Note if cm.ScalarMappable is depreciated, this functionality should be
+ # implemented as format_cursor_data() on ColorizingArtist.
+ n = self.cmap.N
+ if np.ma.getmask(data):
+ return "[]"
+ normed = self.norm(data)
+ if np.isfinite(normed):
+ if isinstance(self.norm, colors.BoundaryNorm):
+ # not an invertible normalization mapping
+ cur_idx = np.argmin(np.abs(self.norm.boundaries - data))
+ neigh_idx = max(0, cur_idx - 1)
+ # use max diff to prevent delta == 0
+ delta = np.diff(
+ self.norm.boundaries[neigh_idx:cur_idx + 2]
+ ).max()
+ elif self.norm.vmin == self.norm.vmax:
+ # singular norms, use delta of 10% of only value
+ delta = np.abs(self.norm.vmin * .1)
+ else:
+ # Midpoints of neighboring color intervals.
+ neighbors = self.norm.inverse(
+ (int(normed * n) + np.array([0, 1])) / n)
+ delta = abs(neighbors - data).max()
+ g_sig_digits = cbook._g_sig_digits(data, delta)
+ else:
+ g_sig_digits = 3 # Consistent with default below.
+ return f"[{data:-#.{g_sig_digits}g}]"
+
+
+class _ScalarMappable(_ColorizerInterface):
+ """
+ A mixin class to map one or multiple sets of scalar data to RGBA.
+
+ The ScalarMappable applies data normalization before returning RGBA colors from
+ the given `~matplotlib.colors.Colormap`.
+ """
+
+ # _ScalarMappable exists for compatibility with
+ # code written before the introduction of the Colorizer
+ # and ColorizingArtist classes.
+
+ # _ScalarMappable can be depreciated so that ColorizingArtist
+ # inherits directly from _ColorizerInterface.
+ # in this case, the following changes should occur:
+ # __init__() has its functionality moved to ColorizingArtist.
+ # set_array(), get_array(), _get_colorizer() and
+ # _check_exclusionary_keywords() are moved to ColorizingArtist.
+ # changed() can be removed so long as colorbar.Colorbar
+ # is changed to connect to the colorizer instead of the
+ # ScalarMappable/ColorizingArtist,
+ # otherwise changed() can be moved to ColorizingArtist.
+ def __init__(self, norm=None, cmap=None, *, colorizer=None, **kwargs):
+ """
+ Parameters
+ ----------
+ norm : `.Normalize` (or subclass thereof) or str or None
+ The normalizing object which scales data, typically into the
+ interval ``[0, 1]``.
+ If a `str`, a `.Normalize` subclass is dynamically generated based
+ on the scale with the corresponding name.
+ If *None*, *norm* defaults to a *colors.Normalize* object which
+ initializes its scaling based on the first data processed.
+ cmap : str or `~matplotlib.colors.Colormap`
+ The colormap used to map normalized data values to RGBA colors.
+ """
+ super().__init__(**kwargs)
+ self._A = None
+ self._colorizer = self._get_colorizer(colorizer=colorizer, norm=norm, cmap=cmap)
+
+ self.colorbar = None
+ self._id_colorizer = self._colorizer.callbacks.connect('changed', self.changed)
+ self.callbacks = cbook.CallbackRegistry(signals=["changed"])
+
+ def set_array(self, A):
+ """
+ Set the value array from array-like *A*.
+
+ Parameters
+ ----------
+ A : array-like or None
+ The values that are mapped to colors.
+
+ The base class `.ScalarMappable` does not make any assumptions on
+ the dimensionality and shape of the value array *A*.
+ """
+ if A is None:
+ self._A = None
+ return
+
+ A = cbook.safe_masked_invalid(A, copy=True)
+ if not np.can_cast(A.dtype, float, "same_kind"):
+ raise TypeError(f"Image data of dtype {A.dtype} cannot be "
+ "converted to float")
+
+ self._A = A
+ if not self.norm.scaled():
+ self._colorizer.autoscale_None(A)
+
+ def get_array(self):
+ """
+ Return the array of values, that are mapped to colors.
+
+ The base class `.ScalarMappable` does not make any assumptions on
+ the dimensionality and shape of the array.
+ """
+ return self._A
+
+ def changed(self):
+ """
+ Call this whenever the mappable is changed to notify all the
+ callbackSM listeners to the 'changed' signal.
+ """
+ self.callbacks.process('changed', self)
+ self.stale = True
+
+ @staticmethod
+ def _check_exclusionary_keywords(colorizer, **kwargs):
+ """
+ Raises a ValueError if any kwarg is not None while colorizer is not None
+ """
+ if colorizer is not None:
+ if any([val is not None for val in kwargs.values()]):
+ raise ValueError("The `colorizer` keyword cannot be used simultaneously"
+ " with any of the following keywords: "
+ + ", ".join(f'`{key}`' for key in kwargs.keys()))
+
+ @staticmethod
+ def _get_colorizer(cmap, norm, colorizer):
+ if isinstance(colorizer, Colorizer):
+ _ScalarMappable._check_exclusionary_keywords(
+ Colorizer, cmap=cmap, norm=norm
+ )
+ return colorizer
+ return Colorizer(cmap, norm)
+
+# The docstrings here must be generic enough to apply to all relevant methods.
+mpl._docstring.interpd.register(
+ cmap_doc="""\
+cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap`
+ The Colormap instance or registered colormap name used to map scalar data
+ to colors.""",
+ norm_doc="""\
+norm : str or `~matplotlib.colors.Normalize`, optional
+ The normalization method used to scale scalar data to the [0, 1] range
+ before mapping to colors using *cmap*. By default, a linear scaling is
+ used, mapping the lowest value to 0 and the highest to 1.
+
+ If given, this can be one of the following:
+
+ - An instance of `.Normalize` or one of its subclasses
+ (see :ref:`colormapnorms`).
+ - A scale name, i.e. one of "linear", "log", "symlog", "logit", etc. For a
+ list of available scales, call `matplotlib.scale.get_scale_names()`.
+ In that case, a suitable `.Normalize` subclass is dynamically generated
+ and instantiated.""",
+ vmin_vmax_doc="""\
+vmin, vmax : float, optional
+ When using scalar data and no explicit *norm*, *vmin* and *vmax* define
+ the data range that the colormap covers. By default, the colormap covers
+ the complete value range of the supplied data. It is an error to use
+ *vmin*/*vmax* when a *norm* instance is given (but using a `str` *norm*
+ name together with *vmin*/*vmax* is acceptable).""",
+)
+
+
+class ColorizingArtist(_ScalarMappable, artist.Artist):
+ """
+ Base class for artists that make map data to color using a `.colorizer.Colorizer`.
+
+ The `.colorizer.Colorizer` applies data normalization before
+ returning RGBA colors from a `~matplotlib.colors.Colormap`.
+
+ """
+ def __init__(self, colorizer, **kwargs):
+ """
+ Parameters
+ ----------
+ colorizer : `.colorizer.Colorizer`
+ """
+ _api.check_isinstance(Colorizer, colorizer=colorizer)
+ super().__init__(colorizer=colorizer, **kwargs)
+
+ @property
+ def colorizer(self):
+ return self._colorizer
+
+ @colorizer.setter
+ def colorizer(self, cl):
+ _api.check_isinstance(Colorizer, colorizer=cl)
+ self._colorizer.callbacks.disconnect(self._id_colorizer)
+ self._colorizer = cl
+ self._id_colorizer = cl.callbacks.connect('changed', self.changed)
+
+ def _set_colorizer_check_keywords(self, colorizer, **kwargs):
+ """
+ Raises a ValueError if any kwarg is not None while colorizer is not None.
+ """
+ self._check_exclusionary_keywords(colorizer, **kwargs)
+ self.colorizer = colorizer
+
+
+def _auto_norm_from_scale(scale_cls):
+ """
+ Automatically generate a norm class from *scale_cls*.
+
+ This differs from `.colors.make_norm_from_scale` in the following points:
+
+ - This function is not a class decorator, but directly returns a norm class
+ (as if decorating `.Normalize`).
+ - The scale is automatically constructed with ``nonpositive="mask"``, if it
+ supports such a parameter, to work around the difference in defaults
+ between standard scales (which use "clip") and norms (which use "mask").
+
+ Note that ``make_norm_from_scale`` caches the generated norm classes
+ (not the instances) and reuses them for later calls. For example,
+ ``type(_auto_norm_from_scale("log")) == LogNorm``.
+ """
+ # Actually try to construct an instance, to verify whether
+ # ``nonpositive="mask"`` is supported.
+ try:
+ norm = colors.make_norm_from_scale(
+ functools.partial(scale_cls, nonpositive="mask"))(
+ colors.Normalize)()
+ except TypeError:
+ norm = colors.make_norm_from_scale(scale_cls)(
+ colors.Normalize)()
+ return type(norm)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/colorizer.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/colorizer.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..8fcce3e5d63ba727efc2cdd18d8a8565b974bac2
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/colorizer.pyi
@@ -0,0 +1,102 @@
+from matplotlib import cbook, colorbar, colors, artist
+
+from typing import overload
+import numpy as np
+from numpy.typing import ArrayLike
+
+
+class Colorizer:
+ colorbar: colorbar.Colorbar | None
+ callbacks: cbook.CallbackRegistry
+ def __init__(
+ self,
+ cmap: str | colors.Colormap | None = ...,
+ norm: str | colors.Normalize | None = ...,
+ ) -> None: ...
+ @property
+ def norm(self) -> colors.Normalize: ...
+ @norm.setter
+ def norm(self, norm: colors.Normalize | str | None) -> None: ...
+ def to_rgba(
+ self,
+ x: np.ndarray,
+ alpha: float | ArrayLike | None = ...,
+ bytes: bool = ...,
+ norm: bool = ...,
+ ) -> np.ndarray: ...
+ def autoscale(self, A: ArrayLike) -> None: ...
+ def autoscale_None(self, A: ArrayLike) -> None: ...
+ @property
+ def cmap(self) -> colors.Colormap: ...
+ @cmap.setter
+ def cmap(self, cmap: colors.Colormap | str | None) -> None: ...
+ def get_clim(self) -> tuple[float, float]: ...
+ def set_clim(self, vmin: float | tuple[float, float] | None = ..., vmax: float | None = ...) -> None: ...
+ def changed(self) -> 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: ...
+
+
+class _ColorizerInterface:
+ cmap: colors.Colormap
+ colorbar: colorbar.Colorbar | None
+ callbacks: cbook.CallbackRegistry
+ def to_rgba(
+ self,
+ x: np.ndarray,
+ alpha: float | ArrayLike | None = ...,
+ bytes: bool = ...,
+ norm: bool = ...,
+ ) -> np.ndarray: ...
+ def get_clim(self) -> tuple[float, float]: ...
+ def set_clim(self, vmin: float | tuple[float, float] | None = ..., vmax: float | None = ...) -> None: ...
+ def get_alpha(self) -> float | None: ...
+ def get_cmap(self) -> colors.Colormap: ...
+ def set_cmap(self, cmap: str | colors.Colormap) -> None: ...
+ @property
+ def norm(self) -> colors.Normalize: ...
+ @norm.setter
+ def norm(self, norm: colors.Normalize | str | None) -> None: ...
+ def set_norm(self, norm: colors.Normalize | str | None) -> None: ...
+ def autoscale(self) -> None: ...
+ def autoscale_None(self) -> None: ...
+
+
+class _ScalarMappable(_ColorizerInterface):
+ def __init__(
+ self,
+ norm: colors.Normalize | None = ...,
+ cmap: str | colors.Colormap | None = ...,
+ *,
+ colorizer: Colorizer | None = ...,
+ **kwargs
+ ) -> None: ...
+ def set_array(self, A: ArrayLike | None) -> None: ...
+ def get_array(self) -> np.ndarray | None: ...
+ def changed(self) -> None: ...
+
+
+class ColorizingArtist(_ScalarMappable, artist.Artist):
+ callbacks: cbook.CallbackRegistry
+ def __init__(
+ self,
+ colorizer: Colorizer,
+ **kwargs
+ ) -> None: ...
+ def set_array(self, A: ArrayLike | None) -> None: ...
+ def get_array(self) -> np.ndarray | None: ...
+ def changed(self) -> None: ...
+ @property
+ def colorizer(self) -> Colorizer: ...
+ @colorizer.setter
+ def colorizer(self, cl: Colorizer) -> None: ...
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/colors.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/colors.py
new file mode 100644
index 0000000000000000000000000000000000000000..aa53b575b7379bafb524388fad125c8c453f0781
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/colors.py
@@ -0,0 +1,3715 @@
+"""
+A module for converting numbers or color arguments to *RGB* or *RGBA*.
+
+*RGB* and *RGBA* are sequences of, respectively, 3 or 4 floats in the
+range 0-1.
+
+This module includes functions and classes for color specification conversions,
+and for mapping numbers to colors in a 1-D array of colors called a colormap.
+
+Mapping data onto colors using a colormap typically involves two steps: a data
+array is first mapped onto the range 0-1 using a subclass of `Normalize`,
+then this number is mapped to a color using a subclass of `Colormap`. Two
+subclasses of `Colormap` provided here: `LinearSegmentedColormap`, which uses
+piecewise-linear interpolation to define colormaps, and `ListedColormap`, which
+makes a colormap from a list of colors.
+
+.. seealso::
+
+ :ref:`colormap-manipulation` for examples of how to
+ make colormaps and
+
+ :ref:`colormaps` for a list of built-in colormaps.
+
+ :ref:`colormapnorms` for more details about data
+ normalization
+
+ More colormaps are available at palettable_.
+
+The module also provides functions for checking whether an object can be
+interpreted as a color (`is_color_like`), for converting such an object
+to an RGBA tuple (`to_rgba`) or to an HTML-like hex string in the
+"#rrggbb" format (`to_hex`), and a sequence of colors to an (n, 4)
+RGBA array (`to_rgba_array`). Caching is used for efficiency.
+
+Colors that Matplotlib recognizes are listed at
+:ref:`colors_def`.
+
+.. _palettable: https://jiffyclub.github.io/palettable/
+.. _xkcd color survey: https://xkcd.com/color/rgb/
+"""
+
+import base64
+from collections.abc import Sized, Sequence, Mapping
+import functools
+import importlib
+import inspect
+import io
+import itertools
+from numbers import Real
+import re
+
+from PIL import Image
+from PIL.PngImagePlugin import PngInfo
+
+import matplotlib as mpl
+import numpy as np
+from matplotlib import _api, _cm, cbook, scale, _image
+from ._color_data import BASE_COLORS, TABLEAU_COLORS, CSS4_COLORS, XKCD_COLORS
+
+
+class _ColorMapping(dict):
+ def __init__(self, mapping):
+ super().__init__(mapping)
+ self.cache = {}
+
+ def __setitem__(self, key, value):
+ super().__setitem__(key, value)
+ self.cache.clear()
+
+ def __delitem__(self, key):
+ super().__delitem__(key)
+ self.cache.clear()
+
+
+_colors_full_map = {}
+# Set by reverse priority order.
+_colors_full_map.update(XKCD_COLORS)
+_colors_full_map.update({k.replace('grey', 'gray'): v
+ for k, v in XKCD_COLORS.items()
+ if 'grey' in k})
+_colors_full_map.update(CSS4_COLORS)
+_colors_full_map.update(TABLEAU_COLORS)
+_colors_full_map.update({k.replace('gray', 'grey'): v
+ for k, v in TABLEAU_COLORS.items()
+ if 'gray' in k})
+_colors_full_map.update(BASE_COLORS)
+_colors_full_map = _ColorMapping(_colors_full_map)
+
+_REPR_PNG_SIZE = (512, 64)
+_BIVAR_REPR_PNG_SIZE = 256
+
+
+def get_named_colors_mapping():
+ """Return the global mapping of names to named colors."""
+ return _colors_full_map
+
+
+class ColorSequenceRegistry(Mapping):
+ r"""
+ Container for sequences of colors that are known to Matplotlib by name.
+
+ The universal registry instance is `matplotlib.color_sequences`. There
+ should be no need for users to instantiate `.ColorSequenceRegistry`
+ themselves.
+
+ Read access uses a dict-like interface mapping names to lists of colors::
+
+ import matplotlib as mpl
+ colors = mpl.color_sequences['tab10']
+
+ For a list of built in color sequences, see :doc:`/gallery/color/color_sequences`.
+ The returned lists are copies, so that their modification does not change
+ the global definition of the color sequence.
+
+ Additional color sequences can be added via
+ `.ColorSequenceRegistry.register`::
+
+ mpl.color_sequences.register('rgb', ['r', 'g', 'b'])
+ """
+
+ _BUILTIN_COLOR_SEQUENCES = {
+ 'tab10': _cm._tab10_data,
+ 'tab20': _cm._tab20_data,
+ 'tab20b': _cm._tab20b_data,
+ 'tab20c': _cm._tab20c_data,
+ 'Pastel1': _cm._Pastel1_data,
+ 'Pastel2': _cm._Pastel2_data,
+ 'Paired': _cm._Paired_data,
+ 'Accent': _cm._Accent_data,
+ 'Dark2': _cm._Dark2_data,
+ 'Set1': _cm._Set1_data,
+ 'Set2': _cm._Set2_data,
+ 'Set3': _cm._Set3_data,
+ 'petroff10': _cm._petroff10_data,
+ }
+
+ def __init__(self):
+ self._color_sequences = {**self._BUILTIN_COLOR_SEQUENCES}
+
+ def __getitem__(self, item):
+ try:
+ return list(self._color_sequences[item])
+ except KeyError:
+ raise KeyError(f"{item!r} is not a known color sequence name")
+
+ def __iter__(self):
+ return iter(self._color_sequences)
+
+ def __len__(self):
+ return len(self._color_sequences)
+
+ def __str__(self):
+ return ('ColorSequenceRegistry; available colormaps:\n' +
+ ', '.join(f"'{name}'" for name in self))
+
+ def register(self, name, color_list):
+ """
+ Register a new color sequence.
+
+ The color sequence registry stores a copy of the given *color_list*, so
+ that future changes to the original list do not affect the registered
+ color sequence. Think of this as the registry taking a snapshot
+ of *color_list* at registration.
+
+ Parameters
+ ----------
+ name : str
+ The name for the color sequence.
+
+ color_list : list of :mpltype:`color`
+ An iterable returning valid Matplotlib colors when iterating over.
+ Note however that the returned color sequence will always be a
+ list regardless of the input type.
+
+ """
+ if name in self._BUILTIN_COLOR_SEQUENCES:
+ raise ValueError(f"{name!r} is a reserved name for a builtin "
+ "color sequence")
+
+ color_list = list(color_list) # force copy and coerce type to list
+ for color in color_list:
+ try:
+ to_rgba(color)
+ except ValueError:
+ raise ValueError(
+ f"{color!r} is not a valid color specification")
+
+ self._color_sequences[name] = color_list
+
+ def unregister(self, name):
+ """
+ Remove a sequence from the registry.
+
+ You cannot remove built-in color sequences.
+
+ If the name is not registered, returns with no error.
+ """
+ if name in self._BUILTIN_COLOR_SEQUENCES:
+ raise ValueError(
+ f"Cannot unregister builtin color sequence {name!r}")
+ self._color_sequences.pop(name, None)
+
+
+_color_sequences = ColorSequenceRegistry()
+
+
+def _sanitize_extrema(ex):
+ if ex is None:
+ return ex
+ try:
+ ret = ex.item()
+ except AttributeError:
+ ret = float(ex)
+ return ret
+
+_nth_color_re = re.compile(r"\AC[0-9]+\Z")
+
+
+def _is_nth_color(c):
+ """Return whether *c* can be interpreted as an item in the color cycle."""
+ return isinstance(c, str) and _nth_color_re.match(c)
+
+
+def is_color_like(c):
+ """Return whether *c* can be interpreted as an RGB(A) color."""
+ # Special-case nth color syntax because it cannot be parsed during setup.
+ if _is_nth_color(c):
+ return True
+ try:
+ to_rgba(c)
+ except (TypeError, ValueError):
+ return False
+ else:
+ return True
+
+
+def _has_alpha_channel(c):
+ """Return whether *c* is a color with an alpha channel."""
+ # 4-element sequences are interpreted as r, g, b, a
+ return not isinstance(c, str) and len(c) == 4
+
+
+def _check_color_like(**kwargs):
+ """
+ For each *key, value* pair in *kwargs*, check that *value* is color-like.
+ """
+ for k, v in kwargs.items():
+ if not is_color_like(v):
+ raise ValueError(
+ f"{v!r} is not a valid value for {k}: supported inputs are "
+ f"(r, g, b) and (r, g, b, a) 0-1 float tuples; "
+ f"'#rrggbb', '#rrggbbaa', '#rgb', '#rgba' strings; "
+ f"named color strings; "
+ f"string reprs of 0-1 floats for grayscale values; "
+ f"'C0', 'C1', ... strings for colors of the color cycle; "
+ f"and pairs combining one of the above with an alpha value")
+
+
+def same_color(c1, c2):
+ """
+ Return whether the colors *c1* and *c2* are the same.
+
+ *c1*, *c2* can be single colors or lists/arrays of colors.
+ """
+ c1 = to_rgba_array(c1)
+ c2 = to_rgba_array(c2)
+ n1 = max(c1.shape[0], 1) # 'none' results in shape (0, 4), but is 1-elem
+ n2 = max(c2.shape[0], 1) # 'none' results in shape (0, 4), but is 1-elem
+
+ if n1 != n2:
+ raise ValueError('Different number of elements passed.')
+ # The following shape test is needed to correctly handle comparisons with
+ # 'none', which results in a shape (0, 4) array and thus cannot be tested
+ # via value comparison.
+ return c1.shape == c2.shape and (c1 == c2).all()
+
+
+def to_rgba(c, alpha=None):
+ """
+ Convert *c* to an RGBA color.
+
+ Parameters
+ ----------
+ c : Matplotlib color or ``np.ma.masked``
+
+ alpha : float, optional
+ If *alpha* is given, force the alpha value of the returned RGBA tuple
+ to *alpha*.
+
+ If None, the alpha value from *c* is used. If *c* does not have an
+ alpha channel, then alpha defaults to 1.
+
+ *alpha* is ignored for the color value ``"none"`` (case-insensitive),
+ which always maps to ``(0, 0, 0, 0)``.
+
+ Returns
+ -------
+ tuple
+ Tuple of floats ``(r, g, b, a)``, where each channel (red, green, blue,
+ alpha) can assume values between 0 and 1.
+ """
+ if isinstance(c, tuple) and len(c) == 2:
+ if alpha is None:
+ c, alpha = c
+ else:
+ c = c[0]
+ # Special-case nth color syntax because it should not be cached.
+ if _is_nth_color(c):
+ prop_cycler = mpl.rcParams['axes.prop_cycle']
+ colors = prop_cycler.by_key().get('color', ['k'])
+ c = colors[int(c[1:]) % len(colors)]
+ try:
+ rgba = _colors_full_map.cache[c, alpha]
+ except (KeyError, TypeError): # Not in cache, or unhashable.
+ rgba = None
+ if rgba is None: # Suppress exception chaining of cache lookup failure.
+ rgba = _to_rgba_no_colorcycle(c, alpha)
+ try:
+ _colors_full_map.cache[c, alpha] = rgba
+ except TypeError:
+ pass
+ return rgba
+
+
+def _to_rgba_no_colorcycle(c, alpha=None):
+ """
+ Convert *c* to an RGBA color, with no support for color-cycle syntax.
+
+ If *alpha* is given, force the alpha value of the returned RGBA tuple
+ to *alpha*. Otherwise, the alpha value from *c* is used, if it has alpha
+ information, or defaults to 1.
+
+ *alpha* is ignored for the color value ``"none"`` (case-insensitive),
+ which always maps to ``(0, 0, 0, 0)``.
+ """
+ if alpha is not None and not 0 <= alpha <= 1:
+ raise ValueError("'alpha' must be between 0 and 1, inclusive")
+ orig_c = c
+ if c is np.ma.masked:
+ return (0., 0., 0., 0.)
+ if isinstance(c, str):
+ if c.lower() == "none":
+ return (0., 0., 0., 0.)
+ # Named color.
+ try:
+ # This may turn c into a non-string, so we check again below.
+ c = _colors_full_map[c]
+ except KeyError:
+ if len(orig_c) != 1:
+ try:
+ c = _colors_full_map[c.lower()]
+ except KeyError:
+ pass
+ if isinstance(c, str):
+ # hex color in #rrggbb format.
+ match = re.match(r"\A#[a-fA-F0-9]{6}\Z", c)
+ if match:
+ return (tuple(int(n, 16) / 255
+ for n in [c[1:3], c[3:5], c[5:7]])
+ + (alpha if alpha is not None else 1.,))
+ # hex color in #rgb format, shorthand for #rrggbb.
+ match = re.match(r"\A#[a-fA-F0-9]{3}\Z", c)
+ if match:
+ return (tuple(int(n, 16) / 255
+ for n in [c[1]*2, c[2]*2, c[3]*2])
+ + (alpha if alpha is not None else 1.,))
+ # hex color with alpha in #rrggbbaa format.
+ match = re.match(r"\A#[a-fA-F0-9]{8}\Z", c)
+ if match:
+ color = [int(n, 16) / 255
+ for n in [c[1:3], c[3:5], c[5:7], c[7:9]]]
+ if alpha is not None:
+ color[-1] = alpha
+ return tuple(color)
+ # hex color with alpha in #rgba format, shorthand for #rrggbbaa.
+ match = re.match(r"\A#[a-fA-F0-9]{4}\Z", c)
+ if match:
+ color = [int(n, 16) / 255
+ for n in [c[1]*2, c[2]*2, c[3]*2, c[4]*2]]
+ if alpha is not None:
+ color[-1] = alpha
+ return tuple(color)
+ # string gray.
+ try:
+ c = float(c)
+ except ValueError:
+ pass
+ else:
+ if not (0 <= c <= 1):
+ raise ValueError(
+ f"Invalid string grayscale value {orig_c!r}. "
+ f"Value must be within 0-1 range")
+ return c, c, c, alpha if alpha is not None else 1.
+ raise ValueError(f"Invalid RGBA argument: {orig_c!r}")
+ # turn 2-D array into 1-D array
+ if isinstance(c, np.ndarray):
+ if c.ndim == 2 and c.shape[0] == 1:
+ c = c.reshape(-1)
+ # tuple color.
+ if not np.iterable(c):
+ raise ValueError(f"Invalid RGBA argument: {orig_c!r}")
+ if len(c) not in [3, 4]:
+ raise ValueError("RGBA sequence should have length 3 or 4")
+ if not all(isinstance(x, Real) for x in c):
+ # Checks that don't work: `map(float, ...)`, `np.array(..., float)` and
+ # `np.array(...).astype(float)` would all convert "0.5" to 0.5.
+ raise ValueError(f"Invalid RGBA argument: {orig_c!r}")
+ # Return a tuple to prevent the cached value from being modified.
+ c = tuple(map(float, c))
+ if len(c) == 3 and alpha is None:
+ alpha = 1
+ if alpha is not None:
+ c = c[:3] + (alpha,)
+ if any(elem < 0 or elem > 1 for elem in c):
+ raise ValueError("RGBA values should be within 0-1 range")
+ return c
+
+
+def to_rgba_array(c, alpha=None):
+ """
+ Convert *c* to a (n, 4) array of RGBA colors.
+
+ Parameters
+ ----------
+ c : Matplotlib color or array of colors
+ If *c* is a masked array, an `~numpy.ndarray` is returned with a
+ (0, 0, 0, 0) row for each masked value or row in *c*.
+
+ alpha : float or sequence of floats, optional
+ If *alpha* is given, force the alpha value of the returned RGBA tuple
+ to *alpha*.
+
+ If None, the alpha value from *c* is used. If *c* does not have an
+ alpha channel, then alpha defaults to 1.
+
+ *alpha* is ignored for the color value ``"none"`` (case-insensitive),
+ which always maps to ``(0, 0, 0, 0)``.
+
+ If *alpha* is a sequence and *c* is a single color, *c* will be
+ repeated to match the length of *alpha*.
+
+ Returns
+ -------
+ array
+ (n, 4) array of RGBA colors, where each channel (red, green, blue,
+ alpha) can assume values between 0 and 1.
+ """
+ if isinstance(c, tuple) and len(c) == 2 and isinstance(c[1], Real):
+ if alpha is None:
+ c, alpha = c
+ else:
+ c = c[0]
+ # Special-case inputs that are already arrays, for performance. (If the
+ # array has the wrong kind or shape, raise the error during one-at-a-time
+ # conversion.)
+ if np.iterable(alpha):
+ alpha = np.asarray(alpha).ravel()
+ if (isinstance(c, np.ndarray) and c.dtype.kind in "if"
+ and c.ndim == 2 and c.shape[1] in [3, 4]):
+ mask = c.mask.any(axis=1) if np.ma.is_masked(c) else None
+ c = np.ma.getdata(c)
+ if np.iterable(alpha):
+ if c.shape[0] == 1 and alpha.shape[0] > 1:
+ c = np.tile(c, (alpha.shape[0], 1))
+ elif c.shape[0] != alpha.shape[0]:
+ raise ValueError("The number of colors must match the number"
+ " of alpha values if there are more than one"
+ " of each.")
+ if c.shape[1] == 3:
+ result = np.column_stack([c, np.zeros(len(c))])
+ result[:, -1] = alpha if alpha is not None else 1.
+ elif c.shape[1] == 4:
+ result = c.copy()
+ if alpha is not None:
+ result[:, -1] = alpha
+ if mask is not None:
+ result[mask] = 0
+ if np.any((result < 0) | (result > 1)):
+ raise ValueError("RGBA values should be within 0-1 range")
+ return result
+ # Handle single values.
+ # Note that this occurs *after* handling inputs that are already arrays, as
+ # `to_rgba(c, alpha)` (below) is expensive for such inputs, due to the need
+ # to format the array in the ValueError message(!).
+ if cbook._str_lower_equal(c, "none"):
+ return np.zeros((0, 4), float)
+ try:
+ if np.iterable(alpha):
+ return np.array([to_rgba(c, a) for a in alpha], float)
+ else:
+ return np.array([to_rgba(c, alpha)], float)
+ except TypeError:
+ pass
+ except ValueError as e:
+ if e.args == ("'alpha' must be between 0 and 1, inclusive", ):
+ # ValueError is from _to_rgba_no_colorcycle().
+ raise e
+ if isinstance(c, str):
+ raise ValueError(f"{c!r} is not a valid color value.")
+
+ if len(c) == 0:
+ return np.zeros((0, 4), float)
+
+ # Quick path if the whole sequence can be directly converted to a numpy
+ # array in one shot.
+ if isinstance(c, Sequence):
+ lens = {len(cc) if isinstance(cc, (list, tuple)) else -1 for cc in c}
+ if lens == {3}:
+ rgba = np.column_stack([c, np.ones(len(c))])
+ elif lens == {4}:
+ rgba = np.array(c)
+ else:
+ rgba = np.array([to_rgba(cc) for cc in c])
+ else:
+ rgba = np.array([to_rgba(cc) for cc in c])
+
+ if alpha is not None:
+ rgba[:, 3] = alpha
+ if isinstance(c, Sequence):
+ # ensure that an explicit alpha does not overwrite full transparency
+ # for "none"
+ none_mask = [cbook._str_equal(cc, "none") for cc in c]
+ rgba[:, 3][none_mask] = 0
+ return rgba
+
+
+def to_rgb(c):
+ """Convert *c* to an RGB color, silently dropping the alpha channel."""
+ return to_rgba(c)[:3]
+
+
+def to_hex(c, keep_alpha=False):
+ """
+ Convert *c* to a hex color.
+
+ Parameters
+ ----------
+ c : :ref:`color ` or `numpy.ma.masked`
+
+ keep_alpha : bool, default: False
+ If False, use the ``#rrggbb`` format, otherwise use ``#rrggbbaa``.
+
+ Returns
+ -------
+ str
+ ``#rrggbb`` or ``#rrggbbaa`` hex color string
+ """
+ c = to_rgba(c)
+ if not keep_alpha:
+ c = c[:3]
+ return "#" + "".join(format(round(val * 255), "02x") for val in c)
+
+
+### Backwards-compatible color-conversion API
+
+
+cnames = CSS4_COLORS
+hexColorPattern = re.compile(r"\A#[a-fA-F0-9]{6}\Z")
+rgb2hex = to_hex
+hex2color = to_rgb
+
+
+class ColorConverter:
+ """
+ A class only kept for backwards compatibility.
+
+ Its functionality is entirely provided by module-level functions.
+ """
+ colors = _colors_full_map
+ cache = _colors_full_map.cache
+ to_rgb = staticmethod(to_rgb)
+ to_rgba = staticmethod(to_rgba)
+ to_rgba_array = staticmethod(to_rgba_array)
+
+
+colorConverter = ColorConverter()
+
+
+### End of backwards-compatible color-conversion API
+
+
+def _create_lookup_table(N, data, gamma=1.0):
+ r"""
+ Create an *N* -element 1D lookup table.
+
+ This assumes a mapping :math:`f : [0, 1] \rightarrow [0, 1]`. The returned
+ data is an array of N values :math:`y = f(x)` where x is sampled from
+ [0, 1].
+
+ By default (*gamma* = 1) x is equidistantly sampled from [0, 1]. The
+ *gamma* correction factor :math:`\gamma` distorts this equidistant
+ sampling by :math:`x \rightarrow x^\gamma`.
+
+ Parameters
+ ----------
+ N : int
+ The number of elements of the created lookup table; at least 1.
+
+ data : (M, 3) array-like or callable
+ Defines the mapping :math:`f`.
+
+ If a (M, 3) array-like, the rows define values (x, y0, y1). The x
+ values must start with x=0, end with x=1, and all x values be in
+ increasing order.
+
+ A value between :math:`x_i` and :math:`x_{i+1}` is mapped to the range
+ :math:`y^1_{i-1} \ldots y^0_i` by linear interpolation.
+
+ For the simple case of a y-continuous mapping, y0 and y1 are identical.
+
+ The two values of y are to allow for discontinuous mapping functions.
+ E.g. a sawtooth with a period of 0.2 and an amplitude of 1 would be::
+
+ [(0, 1, 0), (0.2, 1, 0), (0.4, 1, 0), ..., [(1, 1, 0)]
+
+ In the special case of ``N == 1``, by convention the returned value
+ is y0 for x == 1.
+
+ If *data* is a callable, it must accept and return numpy arrays::
+
+ data(x : ndarray) -> ndarray
+
+ and map values between 0 - 1 to 0 - 1.
+
+ gamma : float
+ Gamma correction factor for input distribution x of the mapping.
+
+ See also https://en.wikipedia.org/wiki/Gamma_correction.
+
+ Returns
+ -------
+ array
+ The lookup table where ``lut[x * (N-1)]`` gives the closest value
+ for values of x between 0 and 1.
+
+ Notes
+ -----
+ This function is internally used for `.LinearSegmentedColormap`.
+ """
+
+ if callable(data):
+ xind = np.linspace(0, 1, N) ** gamma
+ lut = np.clip(np.array(data(xind), dtype=float), 0, 1)
+ return lut
+
+ try:
+ adata = np.array(data)
+ except Exception as err:
+ raise TypeError("data must be convertible to an array") from err
+ _api.check_shape((None, 3), data=adata)
+
+ x = adata[:, 0]
+ y0 = adata[:, 1]
+ y1 = adata[:, 2]
+
+ if x[0] != 0. or x[-1] != 1.0:
+ raise ValueError(
+ "data mapping points must start with x=0 and end with x=1")
+ if (np.diff(x) < 0).any():
+ raise ValueError("data mapping points must have x in increasing order")
+ # begin generation of lookup table
+ if N == 1:
+ # convention: use the y = f(x=1) value for a 1-element lookup table
+ lut = np.array(y0[-1])
+ else:
+ x = x * (N - 1)
+ xind = (N - 1) * np.linspace(0, 1, N) ** gamma
+ ind = np.searchsorted(x, xind)[1:-1]
+
+ distance = (xind[1:-1] - x[ind - 1]) / (x[ind] - x[ind - 1])
+ lut = np.concatenate([
+ [y1[0]],
+ distance * (y0[ind] - y1[ind - 1]) + y1[ind - 1],
+ [y0[-1]],
+ ])
+ # ensure that the lut is confined to values between 0 and 1 by clipping it
+ return np.clip(lut, 0.0, 1.0)
+
+
+class Colormap:
+ """
+ Baseclass for all scalar to RGBA mappings.
+
+ Typically, Colormap instances are used to convert data values (floats)
+ from the interval ``[0, 1]`` to the RGBA color that the respective
+ Colormap represents. For scaling of data into the ``[0, 1]`` interval see
+ `matplotlib.colors.Normalize`. Subclasses of `matplotlib.cm.ScalarMappable`
+ make heavy use of this ``data -> normalize -> map-to-color`` processing
+ chain.
+ """
+
+ def __init__(self, name, N=256):
+ """
+ Parameters
+ ----------
+ name : str
+ The name of the colormap.
+ N : int
+ The number of RGB quantization levels.
+ """
+ self.name = name
+ self.N = int(N) # ensure that N is always int
+ self._rgba_bad = (0.0, 0.0, 0.0, 0.0) # If bad, don't paint anything.
+ self._rgba_under = None
+ self._rgba_over = None
+ self._i_under = self.N
+ self._i_over = self.N + 1
+ self._i_bad = self.N + 2
+ self._isinit = False
+ self.n_variates = 1
+ #: When this colormap exists on a scalar mappable and colorbar_extend
+ #: is not False, colorbar creation will pick up ``colorbar_extend`` as
+ #: the default value for the ``extend`` keyword in the
+ #: `matplotlib.colorbar.Colorbar` constructor.
+ self.colorbar_extend = False
+
+ def __call__(self, X, alpha=None, bytes=False):
+ r"""
+ Parameters
+ ----------
+ X : float or int or array-like
+ The data value(s) to convert to RGBA.
+ For floats, *X* should be in the interval ``[0.0, 1.0]`` to
+ return the RGBA values ``X*100`` percent along the Colormap line.
+ For integers, *X* should be in the interval ``[0, Colormap.N)`` to
+ return RGBA values *indexed* from the Colormap with index ``X``.
+ alpha : float or array-like or None
+ Alpha must be a scalar between 0 and 1, a sequence of such
+ floats with shape matching X, or None.
+ bytes : bool, default: False
+ If False (default), the returned RGBA values will be floats in the
+ interval ``[0, 1]`` otherwise they will be `numpy.uint8`\s in the
+ interval ``[0, 255]``.
+
+ Returns
+ -------
+ Tuple of RGBA values if X is scalar, otherwise an array of
+ RGBA values with a shape of ``X.shape + (4, )``.
+ """
+ rgba, mask = self._get_rgba_and_mask(X, alpha=alpha, bytes=bytes)
+ if not np.iterable(X):
+ rgba = tuple(rgba)
+ return rgba
+
+ def _get_rgba_and_mask(self, X, alpha=None, bytes=False):
+ r"""
+ Parameters
+ ----------
+ X : float or int or array-like
+ The data value(s) to convert to RGBA.
+ For floats, *X* should be in the interval ``[0.0, 1.0]`` to
+ return the RGBA values ``X*100`` percent along the Colormap line.
+ For integers, *X* should be in the interval ``[0, Colormap.N)`` to
+ return RGBA values *indexed* from the Colormap with index ``X``.
+ alpha : float or array-like or None
+ Alpha must be a scalar between 0 and 1, a sequence of such
+ floats with shape matching X, or None.
+ bytes : bool, default: False
+ If False (default), the returned RGBA values will be floats in the
+ interval ``[0, 1]`` otherwise they will be `numpy.uint8`\s in the
+ interval ``[0, 255]``.
+
+ Returns
+ -------
+ colors : np.ndarray
+ Array of RGBA values with a shape of ``X.shape + (4, )``.
+ mask : np.ndarray
+ Boolean array with True where the input is ``np.nan`` or masked.
+ """
+ if not self._isinit:
+ self._init()
+
+ xa = np.array(X, copy=True)
+ if not xa.dtype.isnative:
+ # Native byteorder is faster.
+ xa = xa.byteswap().view(xa.dtype.newbyteorder())
+ if xa.dtype.kind == "f":
+ xa *= self.N
+ # xa == 1 (== N after multiplication) is not out of range.
+ xa[xa == self.N] = self.N - 1
+ # Pre-compute the masks before casting to int (which can truncate
+ # negative values to zero or wrap large floats to negative ints).
+ mask_under = xa < 0
+ mask_over = xa >= self.N
+ # If input was masked, get the bad mask from it; else mask out nans.
+ mask_bad = X.mask if np.ma.is_masked(X) else np.isnan(xa)
+ with np.errstate(invalid="ignore"):
+ # We need this cast for unsigned ints as well as floats
+ xa = xa.astype(int)
+ xa[mask_under] = self._i_under
+ xa[mask_over] = self._i_over
+ xa[mask_bad] = self._i_bad
+
+ lut = self._lut
+ if bytes:
+ lut = (lut * 255).astype(np.uint8)
+
+ rgba = lut.take(xa, axis=0, mode='clip')
+
+ if alpha is not None:
+ alpha = np.clip(alpha, 0, 1)
+ if bytes:
+ alpha *= 255 # Will be cast to uint8 upon assignment.
+ if alpha.shape not in [(), xa.shape]:
+ raise ValueError(
+ f"alpha is array-like but its shape {alpha.shape} does "
+ f"not match that of X {xa.shape}")
+ rgba[..., -1] = alpha
+ # If the "bad" color is all zeros, then ignore alpha input.
+ if (lut[-1] == 0).all():
+ rgba[mask_bad] = (0, 0, 0, 0)
+
+ return rgba, mask_bad
+
+ def __copy__(self):
+ cls = self.__class__
+ cmapobject = cls.__new__(cls)
+ cmapobject.__dict__.update(self.__dict__)
+ if self._isinit:
+ cmapobject._lut = np.copy(self._lut)
+ return cmapobject
+
+ def __eq__(self, other):
+ if (not isinstance(other, Colormap) or
+ self.colorbar_extend != other.colorbar_extend):
+ return False
+ # To compare lookup tables the Colormaps have to be initialized
+ if not self._isinit:
+ self._init()
+ if not other._isinit:
+ other._init()
+ return np.array_equal(self._lut, other._lut)
+
+ def get_bad(self):
+ """Get the color for masked values."""
+ if not self._isinit:
+ self._init()
+ return np.array(self._lut[self._i_bad])
+
+ def set_bad(self, color='k', alpha=None):
+ """Set the color for masked values."""
+ self._rgba_bad = to_rgba(color, alpha)
+ if self._isinit:
+ self._set_extremes()
+
+ def get_under(self):
+ """Get the color for low out-of-range values."""
+ if not self._isinit:
+ self._init()
+ return np.array(self._lut[self._i_under])
+
+ def set_under(self, color='k', alpha=None):
+ """Set the color for low out-of-range values."""
+ self._rgba_under = to_rgba(color, alpha)
+ if self._isinit:
+ self._set_extremes()
+
+ def get_over(self):
+ """Get the color for high out-of-range values."""
+ if not self._isinit:
+ self._init()
+ return np.array(self._lut[self._i_over])
+
+ def set_over(self, color='k', alpha=None):
+ """Set the color for high out-of-range values."""
+ self._rgba_over = to_rgba(color, alpha)
+ if self._isinit:
+ self._set_extremes()
+
+ def set_extremes(self, *, bad=None, under=None, over=None):
+ """
+ Set the colors for masked (*bad*) values and, when ``norm.clip =
+ False``, low (*under*) and high (*over*) out-of-range values.
+ """
+ if bad is not None:
+ self.set_bad(bad)
+ if under is not None:
+ self.set_under(under)
+ if over is not None:
+ self.set_over(over)
+
+ def with_extremes(self, *, bad=None, under=None, over=None):
+ """
+ Return a copy of the colormap, for which the colors for masked (*bad*)
+ values and, when ``norm.clip = False``, low (*under*) and high (*over*)
+ out-of-range values, have been set accordingly.
+ """
+ new_cm = self.copy()
+ new_cm.set_extremes(bad=bad, under=under, over=over)
+ return new_cm
+
+ def _set_extremes(self):
+ if self._rgba_under:
+ self._lut[self._i_under] = self._rgba_under
+ else:
+ self._lut[self._i_under] = self._lut[0]
+ if self._rgba_over:
+ self._lut[self._i_over] = self._rgba_over
+ else:
+ self._lut[self._i_over] = self._lut[self.N - 1]
+ self._lut[self._i_bad] = self._rgba_bad
+
+ def _init(self):
+ """Generate the lookup table, ``self._lut``."""
+ raise NotImplementedError("Abstract class only")
+
+ def is_gray(self):
+ """Return whether the colormap is grayscale."""
+ if not self._isinit:
+ self._init()
+ return (np.all(self._lut[:, 0] == self._lut[:, 1]) and
+ np.all(self._lut[:, 0] == self._lut[:, 2]))
+
+ def resampled(self, lutsize):
+ """Return a new colormap with *lutsize* entries."""
+ if hasattr(self, '_resample'):
+ _api.warn_external(
+ "The ability to resample a color map is now public API "
+ f"However the class {type(self)} still only implements "
+ "the previous private _resample method. Please update "
+ "your class."
+ )
+ return self._resample(lutsize)
+
+ raise NotImplementedError()
+
+ def reversed(self, name=None):
+ """
+ Return a reversed instance of the Colormap.
+
+ .. note:: This function is not implemented for the base class.
+
+ Parameters
+ ----------
+ name : str, optional
+ The name for the reversed colormap. If None, the
+ name is set to ``self.name + "_r"``.
+
+ See Also
+ --------
+ LinearSegmentedColormap.reversed
+ ListedColormap.reversed
+ """
+ raise NotImplementedError()
+
+ def _repr_png_(self):
+ """Generate a PNG representation of the Colormap."""
+ X = np.tile(np.linspace(0, 1, _REPR_PNG_SIZE[0]),
+ (_REPR_PNG_SIZE[1], 1))
+ pixels = self(X, bytes=True)
+ png_bytes = io.BytesIO()
+ title = self.name + ' colormap'
+ author = f'Matplotlib v{mpl.__version__}, https://matplotlib.org'
+ pnginfo = PngInfo()
+ pnginfo.add_text('Title', title)
+ pnginfo.add_text('Description', title)
+ pnginfo.add_text('Author', author)
+ pnginfo.add_text('Software', author)
+ Image.fromarray(pixels).save(png_bytes, format='png', pnginfo=pnginfo)
+ return png_bytes.getvalue()
+
+ def _repr_html_(self):
+ """Generate an HTML representation of the Colormap."""
+ png_bytes = self._repr_png_()
+ png_base64 = base64.b64encode(png_bytes).decode('ascii')
+ def color_block(color):
+ hex_color = to_hex(color, keep_alpha=True)
+ return (f'
')
+
+ return (''
+ f'{self.name} '
+ '
'
+ ''
+ ''
+ '
'
+ f'{color_block(self.get_under())} under'
+ '
'
+ '
'
+ f'bad {color_block(self.get_bad())}'
+ '
'
+ '
'
+ f'over {color_block(self.get_over())}'
+ '
'
+ '
')
+
+ def copy(self):
+ """Return a copy of the colormap."""
+ return self.__copy__()
+
+
+class LinearSegmentedColormap(Colormap):
+ """
+ Colormap objects based on lookup tables using linear segments.
+
+ The lookup table is generated using linear interpolation for each
+ primary color, with the 0-1 domain divided into any number of
+ segments.
+ """
+
+ def __init__(self, name, segmentdata, N=256, gamma=1.0):
+ """
+ Create colormap from linear mapping segments
+
+ segmentdata argument is a dictionary with a red, green and blue
+ entries. Each entry should be a list of *x*, *y0*, *y1* tuples,
+ forming rows in a table. Entries for alpha are optional.
+
+ Example: suppose you want red to increase from 0 to 1 over
+ the bottom half, green to do the same over the middle half,
+ and blue over the top half. Then you would use::
+
+ cdict = {'red': [(0.0, 0.0, 0.0),
+ (0.5, 1.0, 1.0),
+ (1.0, 1.0, 1.0)],
+
+ 'green': [(0.0, 0.0, 0.0),
+ (0.25, 0.0, 0.0),
+ (0.75, 1.0, 1.0),
+ (1.0, 1.0, 1.0)],
+
+ 'blue': [(0.0, 0.0, 0.0),
+ (0.5, 0.0, 0.0),
+ (1.0, 1.0, 1.0)]}
+
+ Each row in the table for a given color is a sequence of
+ *x*, *y0*, *y1* tuples. In each sequence, *x* must increase
+ monotonically from 0 to 1. For any input value *z* falling
+ between *x[i]* and *x[i+1]*, the output value of a given color
+ will be linearly interpolated between *y1[i]* and *y0[i+1]*::
+
+ row i: x y0 y1
+ /
+ /
+ row i+1: x y0 y1
+
+ Hence y0 in the first row and y1 in the last row are never used.
+
+ See Also
+ --------
+ LinearSegmentedColormap.from_list
+ Static method; factory function for generating a smoothly-varying
+ LinearSegmentedColormap.
+ """
+ # True only if all colors in map are identical; needed for contouring.
+ self.monochrome = False
+ super().__init__(name, N)
+ self._segmentdata = segmentdata
+ self._gamma = gamma
+
+ def _init(self):
+ self._lut = np.ones((self.N + 3, 4), float)
+ self._lut[:-3, 0] = _create_lookup_table(
+ self.N, self._segmentdata['red'], self._gamma)
+ self._lut[:-3, 1] = _create_lookup_table(
+ self.N, self._segmentdata['green'], self._gamma)
+ self._lut[:-3, 2] = _create_lookup_table(
+ self.N, self._segmentdata['blue'], self._gamma)
+ if 'alpha' in self._segmentdata:
+ self._lut[:-3, 3] = _create_lookup_table(
+ self.N, self._segmentdata['alpha'], 1)
+ self._isinit = True
+ self._set_extremes()
+
+ def set_gamma(self, gamma):
+ """Set a new gamma value and regenerate colormap."""
+ self._gamma = gamma
+ self._init()
+
+ @staticmethod
+ def from_list(name, colors, N=256, gamma=1.0):
+ """
+ Create a `LinearSegmentedColormap` from a list of colors.
+
+ Parameters
+ ----------
+ name : str
+ The name of the colormap.
+ colors : list of :mpltype:`color` or list of (value, color)
+ If only colors are given, they are equidistantly mapped from the
+ range :math:`[0, 1]`; i.e. 0 maps to ``colors[0]`` and 1 maps to
+ ``colors[-1]``.
+ If (value, color) pairs are given, the mapping is from *value*
+ to *color*. This can be used to divide the range unevenly.
+ N : int
+ The number of RGB quantization levels.
+ gamma : float
+ """
+ if not np.iterable(colors):
+ raise ValueError('colors must be iterable')
+
+ if (isinstance(colors[0], Sized) and len(colors[0]) == 2
+ and not isinstance(colors[0], str)):
+ # List of value, color pairs
+ vals, colors = zip(*colors)
+ else:
+ vals = np.linspace(0, 1, len(colors))
+
+ r, g, b, a = to_rgba_array(colors).T
+ cdict = {
+ "red": np.column_stack([vals, r, r]),
+ "green": np.column_stack([vals, g, g]),
+ "blue": np.column_stack([vals, b, b]),
+ "alpha": np.column_stack([vals, a, a]),
+ }
+
+ return LinearSegmentedColormap(name, cdict, N, gamma)
+
+ def resampled(self, lutsize):
+ """Return a new colormap with *lutsize* entries."""
+ new_cmap = LinearSegmentedColormap(self.name, self._segmentdata,
+ lutsize)
+ new_cmap._rgba_over = self._rgba_over
+ new_cmap._rgba_under = self._rgba_under
+ new_cmap._rgba_bad = self._rgba_bad
+ return new_cmap
+
+ # Helper ensuring picklability of the reversed cmap.
+ @staticmethod
+ def _reverser(func, x):
+ return func(1 - x)
+
+ def reversed(self, name=None):
+ """
+ Return a reversed instance of the Colormap.
+
+ Parameters
+ ----------
+ name : str, optional
+ The name for the reversed colormap. If None, the
+ name is set to ``self.name + "_r"``.
+
+ Returns
+ -------
+ LinearSegmentedColormap
+ The reversed colormap.
+ """
+ if name is None:
+ name = self.name + "_r"
+
+ # Using a partial object keeps the cmap picklable.
+ data_r = {key: (functools.partial(self._reverser, data)
+ if callable(data) else
+ [(1.0 - x, y1, y0) for x, y0, y1 in reversed(data)])
+ for key, data in self._segmentdata.items()}
+
+ new_cmap = LinearSegmentedColormap(name, data_r, self.N, self._gamma)
+ # Reverse the over/under values too
+ new_cmap._rgba_over = self._rgba_under
+ new_cmap._rgba_under = self._rgba_over
+ new_cmap._rgba_bad = self._rgba_bad
+ return new_cmap
+
+
+class ListedColormap(Colormap):
+ """
+ Colormap object generated from a list of colors.
+
+ This may be most useful when indexing directly into a colormap,
+ but it can also be used to generate special colormaps for ordinary
+ mapping.
+
+ Parameters
+ ----------
+ colors : list, array
+ Sequence of Matplotlib color specifications (color names or RGB(A)
+ values).
+ name : str, optional
+ String to identify the colormap.
+ N : int, optional
+ Number of entries in the map. The default is *None*, in which case
+ there is one colormap entry for each element in the list of colors.
+ If ::
+
+ N < len(colors)
+
+ the list will be truncated at *N*. If ::
+
+ N > len(colors)
+
+ the list will be extended by repetition.
+ """
+ def __init__(self, colors, name='from_list', N=None):
+ self.monochrome = False # Are all colors identical? (for contour.py)
+ if N is None:
+ self.colors = colors
+ N = len(colors)
+ else:
+ if isinstance(colors, str):
+ self.colors = [colors] * N
+ self.monochrome = True
+ elif np.iterable(colors):
+ if len(colors) == 1:
+ self.monochrome = True
+ self.colors = list(
+ itertools.islice(itertools.cycle(colors), N))
+ else:
+ try:
+ gray = float(colors)
+ except TypeError:
+ pass
+ else:
+ self.colors = [gray] * N
+ self.monochrome = True
+ super().__init__(name, N)
+
+ def _init(self):
+ self._lut = np.zeros((self.N + 3, 4), float)
+ self._lut[:-3] = to_rgba_array(self.colors)
+ self._isinit = True
+ self._set_extremes()
+
+ def resampled(self, lutsize):
+ """Return a new colormap with *lutsize* entries."""
+ colors = self(np.linspace(0, 1, lutsize))
+ new_cmap = ListedColormap(colors, name=self.name)
+ # Keep the over/under values too
+ new_cmap._rgba_over = self._rgba_over
+ new_cmap._rgba_under = self._rgba_under
+ new_cmap._rgba_bad = self._rgba_bad
+ return new_cmap
+
+ def reversed(self, name=None):
+ """
+ Return a reversed instance of the Colormap.
+
+ Parameters
+ ----------
+ name : str, optional
+ The name for the reversed colormap. If None, the
+ name is set to ``self.name + "_r"``.
+
+ Returns
+ -------
+ ListedColormap
+ A reversed instance of the colormap.
+ """
+ if name is None:
+ name = self.name + "_r"
+
+ colors_r = list(reversed(self.colors))
+ new_cmap = ListedColormap(colors_r, name=name, N=self.N)
+ # Reverse the over/under values too
+ new_cmap._rgba_over = self._rgba_under
+ new_cmap._rgba_under = self._rgba_over
+ new_cmap._rgba_bad = self._rgba_bad
+ return new_cmap
+
+
+class MultivarColormap:
+ """
+ Class for holding multiple `~matplotlib.colors.Colormap` for use in a
+ `~matplotlib.cm.ScalarMappable` object
+ """
+ def __init__(self, colormaps, combination_mode, name='multivariate colormap'):
+ """
+ Parameters
+ ----------
+ colormaps: list or tuple of `~matplotlib.colors.Colormap` objects
+ The individual colormaps that are combined
+ combination_mode: str, 'sRGB_add' or 'sRGB_sub'
+ Describe how colormaps are combined in sRGB space
+
+ - If 'sRGB_add' -> Mixing produces brighter colors
+ `sRGB = sum(colors)`
+ - If 'sRGB_sub' -> Mixing produces darker colors
+ `sRGB = 1 - sum(1 - colors)`
+ name : str, optional
+ The name of the colormap family.
+ """
+ self.name = name
+
+ if not np.iterable(colormaps) \
+ or len(colormaps) == 1 \
+ or isinstance(colormaps, str):
+ raise ValueError("A MultivarColormap must have more than one colormap.")
+ colormaps = list(colormaps) # ensure cmaps is a list, i.e. not a tuple
+ for i, cmap in enumerate(colormaps):
+ if isinstance(cmap, str):
+ colormaps[i] = mpl.colormaps[cmap]
+ elif not isinstance(cmap, Colormap):
+ raise ValueError("colormaps must be a list of objects that subclass"
+ " Colormap or a name found in the colormap registry.")
+
+ self._colormaps = colormaps
+ _api.check_in_list(['sRGB_add', 'sRGB_sub'], combination_mode=combination_mode)
+ self._combination_mode = combination_mode
+ self.n_variates = len(colormaps)
+ self._rgba_bad = (0.0, 0.0, 0.0, 0.0) # If bad, don't paint anything.
+
+ def __call__(self, X, alpha=None, bytes=False, clip=True):
+ r"""
+ Parameters
+ ----------
+ X : tuple (X0, X1, ...) of length equal to the number of colormaps
+ X0, X1 ...:
+ float or int, `~numpy.ndarray` or scalar
+ The data value(s) to convert to RGBA.
+ For floats, *Xi...* should be in the interval ``[0.0, 1.0]`` to
+ return the RGBA values ``X*100`` percent along the Colormap line.
+ For integers, *Xi...* should be in the interval ``[0, self[i].N)`` to
+ return RGBA values *indexed* from colormap [i] with index ``Xi``, where
+ self[i] is colormap i.
+ alpha : float or array-like or None
+ Alpha must be a scalar between 0 and 1, a sequence of such
+ floats with shape matching *Xi*, or None.
+ bytes : bool, default: False
+ If False (default), the returned RGBA values will be floats in the
+ interval ``[0, 1]`` otherwise they will be `numpy.uint8`\s in the
+ interval ``[0, 255]``.
+ clip : bool, default: True
+ If True, clip output to 0 to 1
+
+ Returns
+ -------
+ Tuple of RGBA values if X[0] is scalar, otherwise an array of
+ RGBA values with a shape of ``X.shape + (4, )``.
+ """
+
+ if len(X) != len(self):
+ raise ValueError(
+ f'For the selected colormap the data must have a first dimension '
+ f'{len(self)}, not {len(X)}')
+ rgba, mask_bad = self[0]._get_rgba_and_mask(X[0], bytes=False)
+ for c, xx in zip(self[1:], X[1:]):
+ sub_rgba, sub_mask_bad = c._get_rgba_and_mask(xx, bytes=False)
+ rgba[..., :3] += sub_rgba[..., :3] # add colors
+ rgba[..., 3] *= sub_rgba[..., 3] # multiply alpha
+ mask_bad |= sub_mask_bad
+
+ if self.combination_mode == 'sRGB_sub':
+ rgba[..., :3] -= len(self) - 1
+
+ rgba[mask_bad] = self.get_bad()
+
+ if clip:
+ rgba = np.clip(rgba, 0, 1)
+
+ if alpha is not None:
+ if clip:
+ alpha = np.clip(alpha, 0, 1)
+ if np.shape(alpha) not in [(), np.shape(X[0])]:
+ raise ValueError(
+ f"alpha is array-like but its shape {np.shape(alpha)} does "
+ f"not match that of X[0] {np.shape(X[0])}")
+ rgba[..., -1] *= alpha
+
+ if bytes:
+ if not clip:
+ raise ValueError(
+ "clip cannot be false while bytes is true"
+ " as uint8 does not support values below 0"
+ " or above 255.")
+ rgba = (rgba * 255).astype('uint8')
+
+ if not np.iterable(X[0]):
+ rgba = tuple(rgba)
+
+ return rgba
+
+ def copy(self):
+ """Return a copy of the multivarcolormap."""
+ return self.__copy__()
+
+ def __copy__(self):
+ cls = self.__class__
+ cmapobject = cls.__new__(cls)
+ cmapobject.__dict__.update(self.__dict__)
+ cmapobject._colormaps = [cm.copy() for cm in self._colormaps]
+ cmapobject._rgba_bad = np.copy(self._rgba_bad)
+ return cmapobject
+
+ def __eq__(self, other):
+ if not isinstance(other, MultivarColormap):
+ return False
+ if len(self) != len(other):
+ return False
+ for c0, c1 in zip(self, other):
+ if c0 != c1:
+ return False
+ if not all(self._rgba_bad == other._rgba_bad):
+ return False
+ if self.combination_mode != other.combination_mode:
+ return False
+ return True
+
+ def __getitem__(self, item):
+ return self._colormaps[item]
+
+ def __iter__(self):
+ for c in self._colormaps:
+ yield c
+
+ def __len__(self):
+ return len(self._colormaps)
+
+ def __str__(self):
+ return self.name
+
+ def get_bad(self):
+ """Get the color for masked values."""
+ return np.array(self._rgba_bad)
+
+ def resampled(self, lutshape):
+ """
+ Return a new colormap with *lutshape* entries.
+
+ Parameters
+ ----------
+ lutshape : tuple of (`int`, `None`)
+ The tuple must have a length matching the number of variates.
+ For each element in the tuple, if `int`, the corresponding colorbar
+ is resampled, if `None`, the corresponding colorbar is not resampled.
+
+ Returns
+ -------
+ MultivarColormap
+ """
+
+ if not np.iterable(lutshape) or len(lutshape) != len(self):
+ raise ValueError(f"lutshape must be of length {len(self)}")
+ new_cmap = self.copy()
+ for i, s in enumerate(lutshape):
+ if s is not None:
+ new_cmap._colormaps[i] = self[i].resampled(s)
+ return new_cmap
+
+ def with_extremes(self, *, bad=None, under=None, over=None):
+ """
+ Return a copy of the `MultivarColormap` with modified out-of-range attributes.
+
+ The *bad* keyword modifies the copied `MultivarColormap` while *under* and
+ *over* modifies the attributes of the copied component colormaps.
+ Note that *under* and *over* colors are subject to the mixing rules determined
+ by the *combination_mode*.
+
+ Parameters
+ ----------
+ bad: :mpltype:`color`, default: None
+ If Matplotlib color, the bad value is set accordingly in the copy
+
+ under tuple of :mpltype:`color`, default: None
+ If tuple, the `under` value of each component is set with the values
+ from the tuple.
+
+ over tuple of :mpltype:`color`, default: None
+ If tuple, the `over` value of each component is set with the values
+ from the tuple.
+
+ Returns
+ -------
+ MultivarColormap
+ copy of self with attributes set
+
+ """
+ new_cm = self.copy()
+ if bad is not None:
+ new_cm._rgba_bad = to_rgba(bad)
+ if under is not None:
+ if not np.iterable(under) or len(under) != len(new_cm):
+ raise ValueError("*under* must contain a color for each scalar colormap"
+ f" i.e. be of length {len(new_cm)}.")
+ else:
+ for c, b in zip(new_cm, under):
+ c.set_under(b)
+ if over is not None:
+ if not np.iterable(over) or len(over) != len(new_cm):
+ raise ValueError("*over* must contain a color for each scalar colormap"
+ f" i.e. be of length {len(new_cm)}.")
+ else:
+ for c, b in zip(new_cm, over):
+ c.set_over(b)
+ return new_cm
+
+ @property
+ def combination_mode(self):
+ return self._combination_mode
+
+ def _repr_png_(self):
+ """Generate a PNG representation of the Colormap."""
+ X = np.tile(np.linspace(0, 1, _REPR_PNG_SIZE[0]),
+ (_REPR_PNG_SIZE[1], 1))
+ pixels = np.zeros((_REPR_PNG_SIZE[1]*len(self), _REPR_PNG_SIZE[0], 4),
+ dtype=np.uint8)
+ for i, c in enumerate(self):
+ pixels[i*_REPR_PNG_SIZE[1]:(i+1)*_REPR_PNG_SIZE[1], :] = c(X, bytes=True)
+ png_bytes = io.BytesIO()
+ title = self.name + ' multivariate colormap'
+ author = f'Matplotlib v{mpl.__version__}, https://matplotlib.org'
+ pnginfo = PngInfo()
+ pnginfo.add_text('Title', title)
+ pnginfo.add_text('Description', title)
+ pnginfo.add_text('Author', author)
+ pnginfo.add_text('Software', author)
+ Image.fromarray(pixels).save(png_bytes, format='png', pnginfo=pnginfo)
+ return png_bytes.getvalue()
+
+ def _repr_html_(self):
+ """Generate an HTML representation of the MultivarColormap."""
+ return ''.join([c._repr_html_() for c in self._colormaps])
+
+
+class BivarColormap:
+ """
+ Base class for all bivariate to RGBA mappings.
+
+ Designed as a drop-in replacement for Colormap when using a 2D
+ lookup table. To be used with `~matplotlib.cm.ScalarMappable`.
+ """
+
+ def __init__(self, N=256, M=256, shape='square', origin=(0, 0),
+ name='bivariate colormap'):
+ """
+ Parameters
+ ----------
+ N : int, default: 256
+ The number of RGB quantization levels along the first axis.
+ M : int, default: 256
+ The number of RGB quantization levels along the second axis.
+ shape : {'square', 'circle', 'ignore', 'circleignore'}
+
+ - 'square' each variate is clipped to [0,1] independently
+ - 'circle' the variates are clipped radially to the center
+ of the colormap, and a circular mask is applied when the colormap
+ is displayed
+ - 'ignore' the variates are not clipped, but instead assigned the
+ 'outside' color
+ - 'circleignore' a circular mask is applied, but the data is not
+ clipped and instead assigned the 'outside' color
+
+ origin : (float, float), default: (0,0)
+ The relative origin of the colormap. Typically (0, 0), for colormaps
+ that are linear on both axis, and (.5, .5) for circular colormaps.
+ Used when getting 1D colormaps from 2D colormaps.
+ name : str, optional
+ The name of the colormap.
+ """
+
+ self.name = name
+ self.N = int(N) # ensure that N is always int
+ self.M = int(M)
+ _api.check_in_list(['square', 'circle', 'ignore', 'circleignore'], shape=shape)
+ self._shape = shape
+ self._rgba_bad = (0.0, 0.0, 0.0, 0.0) # If bad, don't paint anything.
+ self._rgba_outside = (1.0, 0.0, 1.0, 1.0)
+ self._isinit = False
+ self.n_variates = 2
+ self._origin = (float(origin[0]), float(origin[1]))
+ '''#: When this colormap exists on a scalar mappable and colorbar_extend
+ #: is not False, colorbar creation will pick up ``colorbar_extend`` as
+ #: the default value for the ``extend`` keyword in the
+ #: `matplotlib.colorbar.Colorbar` constructor.
+ self.colorbar_extend = False'''
+
+ def __call__(self, X, alpha=None, bytes=False):
+ r"""
+ Parameters
+ ----------
+ X : tuple (X0, X1), X0 and X1: float or int or array-like
+ The data value(s) to convert to RGBA.
+
+ - For floats, *X* should be in the interval ``[0.0, 1.0]`` to
+ return the RGBA values ``X*100`` percent along the Colormap.
+ - For integers, *X* should be in the interval ``[0, Colormap.N)`` to
+ return RGBA values *indexed* from the Colormap with index ``X``.
+
+ alpha : float or array-like or None, default: None
+ Alpha must be a scalar between 0 and 1, a sequence of such
+ floats with shape matching X0, or None.
+ bytes : bool, default: False
+ If False (default), the returned RGBA values will be floats in the
+ interval ``[0, 1]`` otherwise they will be `numpy.uint8`\s in the
+ interval ``[0, 255]``.
+
+ Returns
+ -------
+ Tuple of RGBA values if X is scalar, otherwise an array of
+ RGBA values with a shape of ``X.shape + (4, )``.
+ """
+
+ if len(X) != 2:
+ raise ValueError(
+ f'For a `BivarColormap` the data must have a first dimension '
+ f'2, not {len(X)}')
+
+ if not self._isinit:
+ self._init()
+
+ X0 = np.ma.array(X[0], copy=True)
+ X1 = np.ma.array(X[1], copy=True)
+ # clip to shape of colormap, circle square, etc.
+ self._clip((X0, X1))
+
+ # Native byteorder is faster.
+ if not X0.dtype.isnative:
+ X0 = X0.byteswap().view(X0.dtype.newbyteorder())
+ if not X1.dtype.isnative:
+ X1 = X1.byteswap().view(X1.dtype.newbyteorder())
+
+ if X0.dtype.kind == "f":
+ X0 *= self.N
+ # xa == 1 (== N after multiplication) is not out of range.
+ X0[X0 == self.N] = self.N - 1
+
+ if X1.dtype.kind == "f":
+ X1 *= self.M
+ # xa == 1 (== N after multiplication) is not out of range.
+ X1[X1 == self.M] = self.M - 1
+
+ # Pre-compute the masks before casting to int (which can truncate)
+ mask_outside = (X0 < 0) | (X1 < 0) | (X0 >= self.N) | (X1 >= self.M)
+ # If input was masked, get the bad mask from it; else mask out nans.
+ mask_bad_0 = X0.mask if np.ma.is_masked(X0) else np.isnan(X0)
+ mask_bad_1 = X1.mask if np.ma.is_masked(X1) else np.isnan(X1)
+ mask_bad = mask_bad_0 | mask_bad_1
+
+ with np.errstate(invalid="ignore"):
+ # We need this cast for unsigned ints as well as floats
+ X0 = X0.astype(int)
+ X1 = X1.astype(int)
+
+ # Set masked values to zero
+ # The corresponding rgb values will be replaced later
+ for X_part in [X0, X1]:
+ X_part[mask_outside] = 0
+ X_part[mask_bad] = 0
+
+ rgba = self._lut[X0, X1]
+ if np.isscalar(X[0]):
+ rgba = np.copy(rgba)
+ rgba[mask_outside] = self._rgba_outside
+ rgba[mask_bad] = self._rgba_bad
+ if bytes:
+ rgba = (rgba * 255).astype(np.uint8)
+ if alpha is not None:
+ alpha = np.clip(alpha, 0, 1)
+ if bytes:
+ alpha *= 255 # Will be cast to uint8 upon assignment.
+ if np.shape(alpha) not in [(), np.shape(X0)]:
+ raise ValueError(
+ f"alpha is array-like but its shape {np.shape(alpha)} does "
+ f"not match that of X[0] {np.shape(X0)}")
+ rgba[..., -1] = alpha
+ # If the "bad" color is all zeros, then ignore alpha input.
+ if (np.array(self._rgba_bad) == 0).all():
+ rgba[mask_bad] = (0, 0, 0, 0)
+
+ if not np.iterable(X[0]):
+ rgba = tuple(rgba)
+ return rgba
+
+ @property
+ def lut(self):
+ """
+ For external access to the lut, i.e. for displaying the cmap.
+ For circular colormaps this returns a lut with a circular mask.
+
+ Internal functions (such as to_rgb()) should use _lut
+ which stores the lut without a circular mask
+ A lut without the circular mask is needed in to_rgb() because the
+ conversion from floats to ints results in some some pixel-requests
+ just outside of the circular mask
+
+ """
+ if not self._isinit:
+ self._init()
+ lut = np.copy(self._lut)
+ if self.shape == 'circle' or self.shape == 'circleignore':
+ n = np.linspace(-1, 1, self.N)
+ m = np.linspace(-1, 1, self.M)
+ radii_sqr = (n**2)[:, np.newaxis] + (m**2)[np.newaxis, :]
+ mask_outside = radii_sqr > 1
+ lut[mask_outside, 3] = 0
+ return lut
+
+ def __copy__(self):
+ cls = self.__class__
+ cmapobject = cls.__new__(cls)
+ cmapobject.__dict__.update(self.__dict__)
+
+ cmapobject._rgba_outside = np.copy(self._rgba_outside)
+ cmapobject._rgba_bad = np.copy(self._rgba_bad)
+ cmapobject._shape = self.shape
+ if self._isinit:
+ cmapobject._lut = np.copy(self._lut)
+ return cmapobject
+
+ def __eq__(self, other):
+ if not isinstance(other, BivarColormap):
+ return False
+ # To compare lookup tables the Colormaps have to be initialized
+ if not self._isinit:
+ self._init()
+ if not other._isinit:
+ other._init()
+ if not np.array_equal(self._lut, other._lut):
+ return False
+ if not np.array_equal(self._rgba_bad, other._rgba_bad):
+ return False
+ if not np.array_equal(self._rgba_outside, other._rgba_outside):
+ return False
+ if self.shape != other.shape:
+ return False
+ return True
+
+ def get_bad(self):
+ """Get the color for masked values."""
+ return self._rgba_bad
+
+ def get_outside(self):
+ """Get the color for out-of-range values."""
+ return self._rgba_outside
+
+ def resampled(self, lutshape, transposed=False):
+ """
+ Return a new colormap with *lutshape* entries.
+
+ Note that this function does not move the origin.
+
+ Parameters
+ ----------
+ lutshape : tuple of ints or None
+ The tuple must be of length 2, and each entry is either an int or None.
+
+ - If an int, the corresponding axis is resampled.
+ - If negative the corresponding axis is resampled in reverse
+ - If -1, the axis is inverted
+ - If 1 or None, the corresponding axis is not resampled.
+
+ transposed : bool, default: False
+ if True, the axes are swapped after resampling
+
+ Returns
+ -------
+ BivarColormap
+ """
+
+ if not np.iterable(lutshape) or len(lutshape) != 2:
+ raise ValueError("lutshape must be of length 2")
+ lutshape = [lutshape[0], lutshape[1]]
+ if lutshape[0] is None or lutshape[0] == 1:
+ lutshape[0] = self.N
+ if lutshape[1] is None or lutshape[1] == 1:
+ lutshape[1] = self.M
+
+ inverted = [False, False]
+ if lutshape[0] < 0:
+ inverted[0] = True
+ lutshape[0] = -lutshape[0]
+ if lutshape[0] == 1:
+ lutshape[0] = self.N
+ if lutshape[1] < 0:
+ inverted[1] = True
+ lutshape[1] = -lutshape[1]
+ if lutshape[1] == 1:
+ lutshape[1] = self.M
+ x_0, x_1 = np.mgrid[0:1:(lutshape[0] * 1j), 0:1:(lutshape[1] * 1j)]
+ if inverted[0]:
+ x_0 = x_0[::-1, :]
+ if inverted[1]:
+ x_1 = x_1[:, ::-1]
+
+ # we need to use shape = 'square' while resampling the colormap.
+ # if the colormap has shape = 'circle' we would otherwise get *outside* in the
+ # resampled colormap
+ shape_memory = self._shape
+ self._shape = 'square'
+ if transposed:
+ new_lut = self((x_1, x_0))
+ new_cmap = BivarColormapFromImage(new_lut, name=self.name,
+ shape=shape_memory,
+ origin=self.origin[::-1])
+ else:
+ new_lut = self((x_0, x_1))
+ new_cmap = BivarColormapFromImage(new_lut, name=self.name,
+ shape=shape_memory,
+ origin=self.origin)
+ self._shape = shape_memory
+
+ new_cmap._rgba_bad = self._rgba_bad
+ new_cmap._rgba_outside = self._rgba_outside
+ return new_cmap
+
+ def reversed(self, axis_0=True, axis_1=True):
+ """
+ Reverses both or one of the axis.
+ """
+ r_0 = -1 if axis_0 else 1
+ r_1 = -1 if axis_1 else 1
+ return self.resampled((r_0, r_1))
+
+ def transposed(self):
+ """
+ Transposes the colormap by swapping the order of the axis
+ """
+ return self.resampled((None, None), transposed=True)
+
+ def with_extremes(self, *, bad=None, outside=None, shape=None, origin=None):
+ """
+ Return a copy of the `BivarColormap` with modified attributes.
+
+ Note that the *outside* color is only relevant if `shape` = 'ignore'
+ or 'circleignore'.
+
+ Parameters
+ ----------
+ bad : None or :mpltype:`color`
+ If Matplotlib color, the *bad* value is set accordingly in the copy
+
+ outside : None or :mpltype:`color`
+ If Matplotlib color and shape is 'ignore' or 'circleignore', values
+ *outside* the colormap are colored accordingly in the copy
+
+ shape : {'square', 'circle', 'ignore', 'circleignore'}
+
+ - If 'square' each variate is clipped to [0,1] independently
+ - If 'circle' the variates are clipped radially to the center
+ of the colormap, and a circular mask is applied when the colormap
+ is displayed
+ - If 'ignore' the variates are not clipped, but instead assigned the
+ *outside* color
+ - If 'circleignore' a circular mask is applied, but the data is not
+ clipped and instead assigned the *outside* color
+
+ origin : (float, float)
+ The relative origin of the colormap. Typically (0, 0), for colormaps
+ that are linear on both axis, and (.5, .5) for circular colormaps.
+ Used when getting 1D colormaps from 2D colormaps.
+
+ Returns
+ -------
+ BivarColormap
+ copy of self with attributes set
+ """
+ new_cm = self.copy()
+ if bad is not None:
+ new_cm._rgba_bad = to_rgba(bad)
+ if outside is not None:
+ new_cm._rgba_outside = to_rgba(outside)
+ if shape is not None:
+ _api.check_in_list(['square', 'circle', 'ignore', 'circleignore'],
+ shape=shape)
+ new_cm._shape = shape
+ if origin is not None:
+ new_cm._origin = (float(origin[0]), float(origin[1]))
+
+ return new_cm
+
+ def _init(self):
+ """Generate the lookup table, ``self._lut``."""
+ raise NotImplementedError("Abstract class only")
+
+ @property
+ def shape(self):
+ return self._shape
+
+ @property
+ def origin(self):
+ return self._origin
+
+ def _clip(self, X):
+ """
+ For internal use when applying a BivarColormap to data.
+ i.e. cm.ScalarMappable().to_rgba()
+ Clips X[0] and X[1] according to 'self.shape'.
+ X is modified in-place.
+
+ Parameters
+ ----------
+ X: np.array
+ array of floats or ints to be clipped
+ shape : {'square', 'circle', 'ignore', 'circleignore'}
+
+ - If 'square' each variate is clipped to [0,1] independently
+ - If 'circle' the variates are clipped radially to the center
+ of the colormap.
+ It is assumed that a circular mask is applied when the colormap
+ is displayed
+ - If 'ignore' the variates are not clipped, but instead assigned the
+ 'outside' color
+ - If 'circleignore' a circular mask is applied, but the data is not clipped
+ and instead assigned the 'outside' color
+
+ """
+ if self.shape == 'square':
+ for X_part, mx in zip(X, (self.N, self.M)):
+ X_part[X_part < 0] = 0
+ if X_part.dtype.kind == "f":
+ X_part[X_part > 1] = 1
+ else:
+ X_part[X_part >= mx] = mx - 1
+
+ elif self.shape == 'ignore':
+ for X_part, mx in zip(X, (self.N, self.M)):
+ X_part[X_part < 0] = -1
+ if X_part.dtype.kind == "f":
+ X_part[X_part > 1] = -1
+ else:
+ X_part[X_part >= mx] = -1
+
+ elif self.shape == 'circle' or self.shape == 'circleignore':
+ for X_part in X:
+ if X_part.dtype.kind != "f":
+ raise NotImplementedError(
+ "Circular bivariate colormaps are only"
+ " implemented for use with with floats")
+ radii_sqr = (X[0] - 0.5)**2 + (X[1] - 0.5)**2
+ mask_outside = radii_sqr > 0.25
+ if self.shape == 'circle':
+ overextend = 2 * np.sqrt(radii_sqr[mask_outside])
+ X[0][mask_outside] = (X[0][mask_outside] - 0.5) / overextend + 0.5
+ X[1][mask_outside] = (X[1][mask_outside] - 0.5) / overextend + 0.5
+ else:
+ X[0][mask_outside] = -1
+ X[1][mask_outside] = -1
+
+ def __getitem__(self, item):
+ """Creates and returns a colorbar along the selected axis"""
+ if not self._isinit:
+ self._init()
+ if item == 0:
+ origin_1_as_int = int(self._origin[1]*self.M)
+ if origin_1_as_int > self.M-1:
+ origin_1_as_int = self.M-1
+ one_d_lut = self._lut[:, origin_1_as_int]
+ new_cmap = ListedColormap(one_d_lut, name=f'{self.name}_0', N=self.N)
+
+ elif item == 1:
+ origin_0_as_int = int(self._origin[0]*self.N)
+ if origin_0_as_int > self.N-1:
+ origin_0_as_int = self.N-1
+ one_d_lut = self._lut[origin_0_as_int, :]
+ new_cmap = ListedColormap(one_d_lut, name=f'{self.name}_1', N=self.M)
+ else:
+ raise KeyError(f"only 0 or 1 are"
+ f" valid keys for BivarColormap, not {item!r}")
+ new_cmap._rgba_bad = self._rgba_bad
+ if self.shape in ['ignore', 'circleignore']:
+ new_cmap.set_over(self._rgba_outside)
+ new_cmap.set_under(self._rgba_outside)
+ return new_cmap
+
+ def _repr_png_(self):
+ """Generate a PNG representation of the BivarColormap."""
+ if not self._isinit:
+ self._init()
+ pixels = self.lut
+ if pixels.shape[0] < _BIVAR_REPR_PNG_SIZE:
+ pixels = np.repeat(pixels,
+ repeats=_BIVAR_REPR_PNG_SIZE//pixels.shape[0],
+ axis=0)[:256, :]
+ if pixels.shape[1] < _BIVAR_REPR_PNG_SIZE:
+ pixels = np.repeat(pixels,
+ repeats=_BIVAR_REPR_PNG_SIZE//pixels.shape[1],
+ axis=1)[:, :256]
+ pixels = (pixels[::-1, :, :] * 255).astype(np.uint8)
+ png_bytes = io.BytesIO()
+ title = self.name + ' BivarColormap'
+ author = f'Matplotlib v{mpl.__version__}, https://matplotlib.org'
+ pnginfo = PngInfo()
+ pnginfo.add_text('Title', title)
+ pnginfo.add_text('Description', title)
+ pnginfo.add_text('Author', author)
+ pnginfo.add_text('Software', author)
+ Image.fromarray(pixels).save(png_bytes, format='png', pnginfo=pnginfo)
+ return png_bytes.getvalue()
+
+ def _repr_html_(self):
+ """Generate an HTML representation of the Colormap."""
+ png_bytes = self._repr_png_()
+ png_base64 = base64.b64encode(png_bytes).decode('ascii')
+ def color_block(color):
+ hex_color = to_hex(color, keep_alpha=True)
+ return (f'
')
+
+ return (''
+ f'{self.name} '
+ '
'
+ ''
+ ''
+ '
'
+ f'{color_block(self.get_outside())} outside'
+ '
'
+ '
'
+ f'bad {color_block(self.get_bad())}'
+ '
')
+
+ def copy(self):
+ """Return a copy of the colormap."""
+ return self.__copy__()
+
+
+class SegmentedBivarColormap(BivarColormap):
+ """
+ BivarColormap object generated by supersampling a regular grid.
+
+ Parameters
+ ----------
+ patch : np.array
+ Patch is required to have a shape (k, l, 3), and will get supersampled
+ to a lut of shape (N, N, 4).
+ N : int
+ The number of RGB quantization levels along each axis.
+ shape : {'square', 'circle', 'ignore', 'circleignore'}
+
+ - If 'square' each variate is clipped to [0,1] independently
+ - If 'circle' the variates are clipped radially to the center
+ of the colormap, and a circular mask is applied when the colormap
+ is displayed
+ - If 'ignore' the variates are not clipped, but instead assigned the
+ 'outside' color
+ - If 'circleignore' a circular mask is applied, but the data is not clipped
+
+ origin : (float, float)
+ The relative origin of the colormap. Typically (0, 0), for colormaps
+ that are linear on both axis, and (.5, .5) for circular colormaps.
+ Used when getting 1D colormaps from 2D colormaps.
+
+ name : str, optional
+ The name of the colormap.
+ """
+
+ def __init__(self, patch, N=256, shape='square', origin=(0, 0),
+ name='segmented bivariate colormap'):
+ _api.check_shape((None, None, 3), patch=patch)
+ self.patch = patch
+ super().__init__(N, N, shape, origin, name=name)
+
+ def _init(self):
+ s = self.patch.shape
+ _patch = np.empty((s[0], s[1], 4))
+ _patch[:, :, :3] = self.patch
+ _patch[:, :, 3] = 1
+ transform = mpl.transforms.Affine2D().translate(-0.5, -0.5)\
+ .scale(self.N / (s[1] - 1), self.N / (s[0] - 1))
+ self._lut = np.empty((self.N, self.N, 4))
+
+ _image.resample(_patch, self._lut, transform, _image.BILINEAR,
+ resample=False, alpha=1)
+ self._isinit = True
+
+
+class BivarColormapFromImage(BivarColormap):
+ """
+ BivarColormap object generated by supersampling a regular grid.
+
+ Parameters
+ ----------
+ lut : nparray of shape (N, M, 3) or (N, M, 4)
+ The look-up-table
+ shape: {'square', 'circle', 'ignore', 'circleignore'}
+
+ - If 'square' each variate is clipped to [0,1] independently
+ - If 'circle' the variates are clipped radially to the center
+ of the colormap, and a circular mask is applied when the colormap
+ is displayed
+ - If 'ignore' the variates are not clipped, but instead assigned the
+ 'outside' color
+ - If 'circleignore' a circular mask is applied, but the data is not clipped
+
+ origin: (float, float)
+ The relative origin of the colormap. Typically (0, 0), for colormaps
+ that are linear on both axis, and (.5, .5) for circular colormaps.
+ Used when getting 1D colormaps from 2D colormaps.
+ name : str, optional
+ The name of the colormap.
+
+ """
+
+ def __init__(self, lut, shape='square', origin=(0, 0), name='from image'):
+ # We can allow for a PIL.Image as input in the following way, but importing
+ # matplotlib.image.pil_to_array() results in a circular import
+ # For now, this function only accepts numpy arrays.
+ # i.e.:
+ # if isinstance(Image, lut):
+ # lut = image.pil_to_array(lut)
+ lut = np.array(lut, copy=True)
+ if lut.ndim != 3 or lut.shape[2] not in (3, 4):
+ raise ValueError("The lut must be an array of shape (n, m, 3) or (n, m, 4)",
+ " or a PIL.image encoded as RGB or RGBA")
+
+ if lut.dtype == np.uint8:
+ lut = lut.astype(np.float32)/255
+ if lut.shape[2] == 3:
+ new_lut = np.empty((lut.shape[0], lut.shape[1], 4), dtype=lut.dtype)
+ new_lut[:, :, :3] = lut
+ new_lut[:, :, 3] = 1.
+ lut = new_lut
+ self._lut = lut
+ super().__init__(lut.shape[0], lut.shape[1], shape, origin, name=name)
+
+ def _init(self):
+ self._isinit = True
+
+
+class Normalize:
+ """
+ A class which, when called, maps values within the interval
+ ``[vmin, vmax]`` linearly to the interval ``[0.0, 1.0]``. The mapping of
+ values outside ``[vmin, vmax]`` depends on *clip*.
+
+ Examples
+ --------
+ ::
+
+ x = [-2, -1, 0, 1, 2]
+
+ norm = mpl.colors.Normalize(vmin=-1, vmax=1, clip=False)
+ norm(x) # [-0.5, 0., 0.5, 1., 1.5]
+ norm = mpl.colors.Normalize(vmin=-1, vmax=1, clip=True)
+ norm(x) # [0., 0., 0.5, 1., 1.]
+
+ See Also
+ --------
+ :ref:`colormapnorms`
+ """
+
+ def __init__(self, vmin=None, vmax=None, clip=False):
+ """
+ Parameters
+ ----------
+ vmin, vmax : float or None
+ Values within the range ``[vmin, vmax]`` from the input data will be
+ linearly mapped to ``[0, 1]``. If either *vmin* or *vmax* is not
+ provided, they default to the minimum and maximum values of the input,
+ respectively.
+
+ clip : bool, default: False
+ Determines the behavior for mapping values outside the range
+ ``[vmin, vmax]``.
+
+ If clipping is off, values outside the range ``[vmin, vmax]`` are
+ also transformed, resulting in values outside ``[0, 1]``. This
+ behavior is usually desirable, as colormaps can mark these *under*
+ and *over* values with specific colors.
+
+ If clipping is on, values below *vmin* are mapped to 0 and values
+ above *vmax* are mapped to 1. Such values become indistinguishable
+ from regular boundary values, which may cause misinterpretation of
+ the data.
+
+ Notes
+ -----
+ If ``vmin == vmax``, input data will be mapped to 0.
+ """
+ self._vmin = _sanitize_extrema(vmin)
+ self._vmax = _sanitize_extrema(vmax)
+ self._clip = clip
+ self._scale = None
+ self.callbacks = cbook.CallbackRegistry(signals=["changed"])
+
+ @property
+ def vmin(self):
+ return self._vmin
+
+ @vmin.setter
+ def vmin(self, value):
+ value = _sanitize_extrema(value)
+ if value != self._vmin:
+ self._vmin = value
+ self._changed()
+
+ @property
+ def vmax(self):
+ return self._vmax
+
+ @vmax.setter
+ def vmax(self, value):
+ value = _sanitize_extrema(value)
+ if value != self._vmax:
+ self._vmax = value
+ self._changed()
+
+ @property
+ def clip(self):
+ return self._clip
+
+ @clip.setter
+ def clip(self, value):
+ if value != self._clip:
+ self._clip = value
+ self._changed()
+
+ def _changed(self):
+ """
+ Call this whenever the norm is changed to notify all the
+ callback listeners to the 'changed' signal.
+ """
+ self.callbacks.process('changed')
+
+ @staticmethod
+ def process_value(value):
+ """
+ Homogenize the input *value* for easy and efficient normalization.
+
+ *value* can be a scalar or sequence.
+
+ Parameters
+ ----------
+ value
+ Data to normalize.
+
+ Returns
+ -------
+ result : masked array
+ Masked array with the same shape as *value*.
+ is_scalar : bool
+ Whether *value* is a scalar.
+
+ Notes
+ -----
+ Float dtypes are preserved; integer types with two bytes or smaller are
+ converted to np.float32, and larger types are converted to np.float64.
+ Preserving float32 when possible, and using in-place operations,
+ greatly improves speed for large arrays.
+ """
+ is_scalar = not np.iterable(value)
+ if is_scalar:
+ value = [value]
+ dtype = np.min_scalar_type(value)
+ if np.issubdtype(dtype, np.integer) or dtype.type is np.bool_:
+ # bool_/int8/int16 -> float32; int32/int64 -> float64
+ dtype = np.promote_types(dtype, np.float32)
+ # ensure data passed in as an ndarray subclass are interpreted as
+ # an ndarray. See issue #6622.
+ mask = np.ma.getmask(value)
+ data = np.asarray(value)
+ result = np.ma.array(data, mask=mask, dtype=dtype, copy=True)
+ return result, is_scalar
+
+ def __call__(self, value, clip=None):
+ """
+ Normalize the data and return the normalized data.
+
+ Parameters
+ ----------
+ value
+ Data to normalize.
+ clip : bool, optional
+ See the description of the parameter *clip* in `.Normalize`.
+
+ If ``None``, defaults to ``self.clip`` (which defaults to
+ ``False``).
+
+ Notes
+ -----
+ If not already initialized, ``self.vmin`` and ``self.vmax`` are
+ initialized using ``self.autoscale_None(value)``.
+ """
+ if clip is None:
+ clip = self.clip
+
+ result, is_scalar = self.process_value(value)
+
+ if self.vmin is None or self.vmax is None:
+ self.autoscale_None(result)
+ # Convert at least to float, without losing precision.
+ (vmin,), _ = self.process_value(self.vmin)
+ (vmax,), _ = self.process_value(self.vmax)
+ if vmin == vmax:
+ result.fill(0) # Or should it be all masked? Or 0.5?
+ elif vmin > vmax:
+ raise ValueError("minvalue must be less than or equal to maxvalue")
+ else:
+ if clip:
+ mask = np.ma.getmask(result)
+ result = np.ma.array(np.clip(result.filled(vmax), vmin, vmax),
+ mask=mask)
+ # ma division is very slow; we can take a shortcut
+ resdat = result.data
+ resdat -= vmin
+ resdat /= (vmax - vmin)
+ result = np.ma.array(resdat, mask=result.mask, copy=False)
+ if is_scalar:
+ result = result[0]
+ return result
+
+ def inverse(self, value):
+ """
+ Maps the normalized value (i.e., index in the colormap) back to image
+ data value.
+
+ Parameters
+ ----------
+ value
+ Normalized value.
+ """
+ if not self.scaled():
+ raise ValueError("Not invertible until both vmin and vmax are set")
+ (vmin,), _ = self.process_value(self.vmin)
+ (vmax,), _ = self.process_value(self.vmax)
+
+ if np.iterable(value):
+ val = np.ma.asarray(value)
+ return vmin + val * (vmax - vmin)
+ else:
+ return vmin + value * (vmax - vmin)
+
+ def autoscale(self, A):
+ """Set *vmin*, *vmax* to min, max of *A*."""
+ with self.callbacks.blocked():
+ # Pause callbacks while we are updating so we only get
+ # a single update signal at the end
+ self.vmin = self.vmax = None
+ self.autoscale_None(A)
+ self._changed()
+
+ def autoscale_None(self, A):
+ """If *vmin* or *vmax* are not set, use the min/max of *A* to set them."""
+ A = np.asanyarray(A)
+
+ if isinstance(A, np.ma.MaskedArray):
+ # we need to make the distinction between an array, False, np.bool_(False)
+ if A.mask is False or not A.mask.shape:
+ A = A.data
+
+ if self.vmin is None and A.size:
+ self.vmin = A.min()
+ if self.vmax is None and A.size:
+ self.vmax = A.max()
+
+ def scaled(self):
+ """Return whether *vmin* and *vmax* are both set."""
+ return self.vmin is not None and self.vmax is not None
+
+
+class TwoSlopeNorm(Normalize):
+ def __init__(self, vcenter, vmin=None, vmax=None):
+ """
+ Normalize data with a set center.
+
+ Useful when mapping data with an unequal rates of change around a
+ conceptual center, e.g., data that range from -2 to 4, with 0 as
+ the midpoint.
+
+ Parameters
+ ----------
+ vcenter : float
+ The data value that defines ``0.5`` in the normalization.
+ vmin : float, optional
+ The data value that defines ``0.0`` in the normalization.
+ Defaults to the min value of the dataset.
+ vmax : float, optional
+ The data value that defines ``1.0`` in the normalization.
+ Defaults to the max value of the dataset.
+
+ Examples
+ --------
+ This maps data value -4000 to 0., 0 to 0.5, and +10000 to 1.0; data
+ between is linearly interpolated::
+
+ >>> import matplotlib.colors as mcolors
+ >>> offset = mcolors.TwoSlopeNorm(vmin=-4000.,
+ ... vcenter=0., vmax=10000)
+ >>> data = [-4000., -2000., 0., 2500., 5000., 7500., 10000.]
+ >>> offset(data)
+ array([0., 0.25, 0.5, 0.625, 0.75, 0.875, 1.0])
+ """
+
+ super().__init__(vmin=vmin, vmax=vmax)
+ self._vcenter = vcenter
+ if vcenter is not None and vmax is not None and vcenter >= vmax:
+ raise ValueError('vmin, vcenter, and vmax must be in '
+ 'ascending order')
+ if vcenter is not None and vmin is not None and vcenter <= vmin:
+ raise ValueError('vmin, vcenter, and vmax must be in '
+ 'ascending order')
+
+ @property
+ def vcenter(self):
+ return self._vcenter
+
+ @vcenter.setter
+ def vcenter(self, value):
+ if value != self._vcenter:
+ self._vcenter = value
+ self._changed()
+
+ def autoscale_None(self, A):
+ """
+ Get vmin and vmax.
+
+ If vcenter isn't in the range [vmin, vmax], either vmin or vmax
+ is expanded so that vcenter lies in the middle of the modified range
+ [vmin, vmax].
+ """
+ super().autoscale_None(A)
+ if self.vmin >= self.vcenter:
+ self.vmin = self.vcenter - (self.vmax - self.vcenter)
+ if self.vmax <= self.vcenter:
+ self.vmax = self.vcenter + (self.vcenter - self.vmin)
+
+ def __call__(self, value, clip=None):
+ """
+ Map value to the interval [0, 1]. The *clip* argument is unused.
+ """
+ result, is_scalar = self.process_value(value)
+ self.autoscale_None(result) # sets self.vmin, self.vmax if None
+
+ if not self.vmin <= self.vcenter <= self.vmax:
+ raise ValueError("vmin, vcenter, vmax must increase monotonically")
+ # note that we must extrapolate for tick locators:
+ result = np.ma.masked_array(
+ np.interp(result, [self.vmin, self.vcenter, self.vmax],
+ [0, 0.5, 1], left=-np.inf, right=np.inf),
+ mask=np.ma.getmask(result))
+ if is_scalar:
+ result = np.atleast_1d(result)[0]
+ return result
+
+ def inverse(self, value):
+ if not self.scaled():
+ raise ValueError("Not invertible until both vmin and vmax are set")
+ (vmin,), _ = self.process_value(self.vmin)
+ (vmax,), _ = self.process_value(self.vmax)
+ (vcenter,), _ = self.process_value(self.vcenter)
+ result = np.interp(value, [0, 0.5, 1], [vmin, vcenter, vmax],
+ left=-np.inf, right=np.inf)
+ return result
+
+
+class CenteredNorm(Normalize):
+ def __init__(self, vcenter=0, halfrange=None, clip=False):
+ """
+ Normalize symmetrical data around a center (0 by default).
+
+ Unlike `TwoSlopeNorm`, `CenteredNorm` applies an equal rate of change
+ around the center.
+
+ Useful when mapping symmetrical data around a conceptual center
+ e.g., data that range from -2 to 4, with 0 as the midpoint, and
+ with equal rates of change around that midpoint.
+
+ Parameters
+ ----------
+ vcenter : float, default: 0
+ The data value that defines ``0.5`` in the normalization.
+ halfrange : float, optional
+ The range of data values that defines a range of ``0.5`` in the
+ normalization, so that *vcenter* - *halfrange* is ``0.0`` and
+ *vcenter* + *halfrange* is ``1.0`` in the normalization.
+ Defaults to the largest absolute difference to *vcenter* for
+ the values in the dataset.
+ clip : bool, default: False
+ Determines the behavior for mapping values outside the range
+ ``[vmin, vmax]``.
+
+ If clipping is off, values outside the range ``[vmin, vmax]`` are
+ also transformed, resulting in values outside ``[0, 1]``. This
+ behavior is usually desirable, as colormaps can mark these *under*
+ and *over* values with specific colors.
+
+ If clipping is on, values below *vmin* are mapped to 0 and values
+ above *vmax* are mapped to 1. Such values become indistinguishable
+ from regular boundary values, which may cause misinterpretation of
+ the data.
+
+ Examples
+ --------
+ This maps data values -2 to 0.25, 0 to 0.5, and 4 to 1.0
+ (assuming equal rates of change above and below 0.0):
+
+ >>> import matplotlib.colors as mcolors
+ >>> norm = mcolors.CenteredNorm(halfrange=4.0)
+ >>> data = [-2., 0., 4.]
+ >>> norm(data)
+ array([0.25, 0.5 , 1. ])
+ """
+ super().__init__(vmin=None, vmax=None, clip=clip)
+ self._vcenter = vcenter
+ # calling the halfrange setter to set vmin and vmax
+ self.halfrange = halfrange
+
+ def autoscale(self, A):
+ """
+ Set *halfrange* to ``max(abs(A-vcenter))``, then set *vmin* and *vmax*.
+ """
+ A = np.asanyarray(A)
+ self.halfrange = max(self._vcenter-A.min(),
+ A.max()-self._vcenter)
+
+ def autoscale_None(self, A):
+ """Set *vmin* and *vmax*."""
+ A = np.asanyarray(A)
+ if self.halfrange is None and A.size:
+ self.autoscale(A)
+
+ @property
+ def vmin(self):
+ return self._vmin
+
+ @vmin.setter
+ def vmin(self, value):
+ value = _sanitize_extrema(value)
+ if value != self._vmin:
+ self._vmin = value
+ self._vmax = 2*self.vcenter - value
+ self._changed()
+
+ @property
+ def vmax(self):
+ return self._vmax
+
+ @vmax.setter
+ def vmax(self, value):
+ value = _sanitize_extrema(value)
+ if value != self._vmax:
+ self._vmax = value
+ self._vmin = 2*self.vcenter - value
+ self._changed()
+
+ @property
+ def vcenter(self):
+ return self._vcenter
+
+ @vcenter.setter
+ def vcenter(self, vcenter):
+ if vcenter != self._vcenter:
+ self._vcenter = vcenter
+ # Trigger an update of the vmin/vmax values through the setter
+ self.halfrange = self.halfrange
+ self._changed()
+
+ @property
+ def halfrange(self):
+ if self.vmin is None or self.vmax is None:
+ return None
+ return (self.vmax - self.vmin) / 2
+
+ @halfrange.setter
+ def halfrange(self, halfrange):
+ if halfrange is None:
+ self.vmin = None
+ self.vmax = None
+ else:
+ self.vmin = self.vcenter - abs(halfrange)
+ self.vmax = self.vcenter + abs(halfrange)
+
+
+def make_norm_from_scale(scale_cls, base_norm_cls=None, *, init=None):
+ """
+ Decorator for building a `.Normalize` subclass from a `~.scale.ScaleBase`
+ subclass.
+
+ After ::
+
+ @make_norm_from_scale(scale_cls)
+ class norm_cls(Normalize):
+ ...
+
+ *norm_cls* is filled with methods so that normalization computations are
+ forwarded to *scale_cls* (i.e., *scale_cls* is the scale that would be used
+ for the colorbar of a mappable normalized with *norm_cls*).
+
+ If *init* is not passed, then the constructor signature of *norm_cls*
+ will be ``norm_cls(vmin=None, vmax=None, clip=False)``; these three
+ parameters will be forwarded to the base class (``Normalize.__init__``),
+ and a *scale_cls* object will be initialized with no arguments (other than
+ a dummy axis).
+
+ If the *scale_cls* constructor takes additional parameters, then *init*
+ should be passed to `make_norm_from_scale`. It is a callable which is
+ *only* used for its signature. First, this signature will become the
+ signature of *norm_cls*. Second, the *norm_cls* constructor will bind the
+ parameters passed to it using this signature, extract the bound *vmin*,
+ *vmax*, and *clip* values, pass those to ``Normalize.__init__``, and
+ forward the remaining bound values (including any defaults defined by the
+ signature) to the *scale_cls* constructor.
+ """
+
+ if base_norm_cls is None:
+ return functools.partial(make_norm_from_scale, scale_cls, init=init)
+
+ if isinstance(scale_cls, functools.partial):
+ scale_args = scale_cls.args
+ scale_kwargs_items = tuple(scale_cls.keywords.items())
+ scale_cls = scale_cls.func
+ else:
+ scale_args = scale_kwargs_items = ()
+
+ if init is None:
+ def init(vmin=None, vmax=None, clip=False): pass
+
+ return _make_norm_from_scale(
+ scale_cls, scale_args, scale_kwargs_items,
+ base_norm_cls, inspect.signature(init))
+
+
+@functools.cache
+def _make_norm_from_scale(
+ scale_cls, scale_args, scale_kwargs_items,
+ base_norm_cls, bound_init_signature,
+):
+ """
+ Helper for `make_norm_from_scale`.
+
+ This function is split out to enable caching (in particular so that
+ different unpickles reuse the same class). In order to do so,
+
+ - ``functools.partial`` *scale_cls* is expanded into ``func, args, kwargs``
+ to allow memoizing returned norms (partial instances always compare
+ unequal, but we can check identity based on ``func, args, kwargs``;
+ - *init* is replaced by *init_signature*, as signatures are picklable,
+ unlike to arbitrary lambdas.
+ """
+
+ class Norm(base_norm_cls):
+ def __reduce__(self):
+ cls = type(self)
+ # If the class is toplevel-accessible, it is possible to directly
+ # pickle it "by name". This is required to support norm classes
+ # defined at a module's toplevel, as the inner base_norm_cls is
+ # otherwise unpicklable (as it gets shadowed by the generated norm
+ # class). If either import or attribute access fails, fall back to
+ # the general path.
+ try:
+ if cls is getattr(importlib.import_module(cls.__module__),
+ cls.__qualname__):
+ return (_create_empty_object_of_class, (cls,), vars(self))
+ except (ImportError, AttributeError):
+ pass
+ return (_picklable_norm_constructor,
+ (scale_cls, scale_args, scale_kwargs_items,
+ base_norm_cls, bound_init_signature),
+ vars(self))
+
+ def __init__(self, *args, **kwargs):
+ ba = bound_init_signature.bind(*args, **kwargs)
+ ba.apply_defaults()
+ super().__init__(
+ **{k: ba.arguments.pop(k) for k in ["vmin", "vmax", "clip"]})
+ self._scale = functools.partial(
+ scale_cls, *scale_args, **dict(scale_kwargs_items))(
+ axis=None, **ba.arguments)
+ self._trf = self._scale.get_transform()
+
+ __init__.__signature__ = bound_init_signature.replace(parameters=[
+ inspect.Parameter("self", inspect.Parameter.POSITIONAL_OR_KEYWORD),
+ *bound_init_signature.parameters.values()])
+
+ def __call__(self, value, clip=None):
+ value, is_scalar = self.process_value(value)
+ if self.vmin is None or self.vmax is None:
+ self.autoscale_None(value)
+ if self.vmin > self.vmax:
+ raise ValueError("vmin must be less or equal to vmax")
+ if self.vmin == self.vmax:
+ return np.full_like(value, 0)
+ if clip is None:
+ clip = self.clip
+ if clip:
+ value = np.clip(value, self.vmin, self.vmax)
+ t_value = self._trf.transform(value).reshape(np.shape(value))
+ t_vmin, t_vmax = self._trf.transform([self.vmin, self.vmax])
+ if not np.isfinite([t_vmin, t_vmax]).all():
+ raise ValueError("Invalid vmin or vmax")
+ t_value -= t_vmin
+ t_value /= (t_vmax - t_vmin)
+ t_value = np.ma.masked_invalid(t_value, copy=False)
+ return t_value[0] if is_scalar else t_value
+
+ def inverse(self, value):
+ if not self.scaled():
+ raise ValueError("Not invertible until scaled")
+ if self.vmin > self.vmax:
+ raise ValueError("vmin must be less or equal to vmax")
+ t_vmin, t_vmax = self._trf.transform([self.vmin, self.vmax])
+ if not np.isfinite([t_vmin, t_vmax]).all():
+ raise ValueError("Invalid vmin or vmax")
+ value, is_scalar = self.process_value(value)
+ rescaled = value * (t_vmax - t_vmin)
+ rescaled += t_vmin
+ value = (self._trf
+ .inverted()
+ .transform(rescaled)
+ .reshape(np.shape(value)))
+ return value[0] if is_scalar else value
+
+ def autoscale_None(self, A):
+ # i.e. A[np.isfinite(...)], but also for non-array A's
+ in_trf_domain = np.extract(np.isfinite(self._trf.transform(A)), A)
+ if in_trf_domain.size == 0:
+ in_trf_domain = np.ma.masked
+ return super().autoscale_None(in_trf_domain)
+
+ if base_norm_cls is Normalize:
+ Norm.__name__ = f"{scale_cls.__name__}Norm"
+ Norm.__qualname__ = f"{scale_cls.__qualname__}Norm"
+ else:
+ Norm.__name__ = base_norm_cls.__name__
+ Norm.__qualname__ = base_norm_cls.__qualname__
+ Norm.__module__ = base_norm_cls.__module__
+ Norm.__doc__ = base_norm_cls.__doc__
+
+ return Norm
+
+
+def _create_empty_object_of_class(cls):
+ return cls.__new__(cls)
+
+
+def _picklable_norm_constructor(*args):
+ return _create_empty_object_of_class(_make_norm_from_scale(*args))
+
+
+@make_norm_from_scale(
+ scale.FuncScale,
+ init=lambda functions, vmin=None, vmax=None, clip=False: None)
+class FuncNorm(Normalize):
+ """
+ Arbitrary normalization using functions for the forward and inverse.
+
+ Parameters
+ ----------
+ functions : (callable, callable)
+ two-tuple of the forward and inverse functions for the normalization.
+ The forward function must be monotonic.
+
+ Both functions must have the signature ::
+
+ def forward(values: array-like) -> array-like
+
+ vmin, vmax : float or None
+ If *vmin* and/or *vmax* is not given, they are initialized from the
+ minimum and maximum value, respectively, of the first input
+ processed; i.e., ``__call__(A)`` calls ``autoscale_None(A)``.
+
+ clip : bool, default: False
+ Determines the behavior for mapping values outside the range
+ ``[vmin, vmax]``.
+
+ If clipping is off, values outside the range ``[vmin, vmax]`` are also
+ transformed by the function, resulting in values outside ``[0, 1]``.
+ This behavior is usually desirable, as colormaps can mark these *under*
+ and *over* values with specific colors.
+
+ If clipping is on, values below *vmin* are mapped to 0 and values above
+ *vmax* are mapped to 1. Such values become indistinguishable from
+ regular boundary values, which may cause misinterpretation of the data.
+ """
+
+
+LogNorm = make_norm_from_scale(
+ functools.partial(scale.LogScale, nonpositive="mask"))(Normalize)
+LogNorm.__name__ = LogNorm.__qualname__ = "LogNorm"
+LogNorm.__doc__ = "Normalize a given value to the 0-1 range on a log scale."
+
+
+@make_norm_from_scale(
+ scale.SymmetricalLogScale,
+ init=lambda linthresh, linscale=1., vmin=None, vmax=None, clip=False, *,
+ base=10: None)
+class SymLogNorm(Normalize):
+ """
+ The symmetrical logarithmic scale is logarithmic in both the
+ positive and negative directions from the origin.
+
+ Since the values close to zero tend toward infinity, there is a
+ need to have a range around zero that is linear. The parameter
+ *linthresh* allows the user to specify the size of this range
+ (-*linthresh*, *linthresh*).
+
+ Parameters
+ ----------
+ linthresh : float
+ The range within which the plot is linear (to avoid having the plot
+ go to infinity around zero).
+ linscale : float, default: 1
+ This allows the linear range (-*linthresh* to *linthresh*) to be
+ stretched relative to the logarithmic range. Its value is the
+ number of decades to use for each half of the linear range. For
+ example, when *linscale* == 1.0 (the default), the space used for
+ the positive and negative halves of the linear range will be equal
+ to one decade in the logarithmic range.
+ base : float, default: 10
+ """
+
+ @property
+ def linthresh(self):
+ return self._scale.linthresh
+
+ @linthresh.setter
+ def linthresh(self, value):
+ self._scale.linthresh = value
+
+
+@make_norm_from_scale(
+ scale.AsinhScale,
+ init=lambda linear_width=1, vmin=None, vmax=None, clip=False: None)
+class AsinhNorm(Normalize):
+ """
+ The inverse hyperbolic sine scale is approximately linear near
+ the origin, but becomes logarithmic for larger positive
+ or negative values. Unlike the `SymLogNorm`, the transition between
+ these linear and logarithmic regions is smooth, which may reduce
+ the risk of visual artifacts.
+
+ .. note::
+
+ This API is provisional and may be revised in the future
+ based on early user feedback.
+
+ Parameters
+ ----------
+ linear_width : float, default: 1
+ The effective width of the linear region, beyond which
+ the transformation becomes asymptotically logarithmic
+ """
+
+ @property
+ def linear_width(self):
+ return self._scale.linear_width
+
+ @linear_width.setter
+ def linear_width(self, value):
+ self._scale.linear_width = value
+
+
+class PowerNorm(Normalize):
+ r"""
+ Linearly map a given value to the 0-1 range and then apply
+ a power-law normalization over that range.
+
+ Parameters
+ ----------
+ gamma : float
+ Power law exponent.
+ vmin, vmax : float or None
+ If *vmin* and/or *vmax* is not given, they are initialized from the
+ minimum and maximum value, respectively, of the first input
+ processed; i.e., ``__call__(A)`` calls ``autoscale_None(A)``.
+ clip : bool, default: False
+ Determines the behavior for mapping values outside the range
+ ``[vmin, vmax]``.
+
+ If clipping is off, values above *vmax* are transformed by the power
+ function, resulting in values above 1, and values below *vmin* are linearly
+ transformed resulting in values below 0. This behavior is usually desirable, as
+ colormaps can mark these *under* and *over* values with specific colors.
+
+ If clipping is on, values below *vmin* are mapped to 0 and values above
+ *vmax* are mapped to 1. Such values become indistinguishable from
+ regular boundary values, which may cause misinterpretation of the data.
+
+ Notes
+ -----
+ The normalization formula is
+
+ .. math::
+
+ \left ( \frac{x - v_{min}}{v_{max} - v_{min}} \right )^{\gamma}
+
+ For input values below *vmin*, gamma is set to one.
+ """
+ def __init__(self, gamma, vmin=None, vmax=None, clip=False):
+ super().__init__(vmin, vmax, clip)
+ self.gamma = gamma
+
+ def __call__(self, value, clip=None):
+ if clip is None:
+ clip = self.clip
+
+ result, is_scalar = self.process_value(value)
+
+ self.autoscale_None(result)
+ gamma = self.gamma
+ vmin, vmax = self.vmin, self.vmax
+ if vmin > vmax:
+ raise ValueError("minvalue must be less than or equal to maxvalue")
+ elif vmin == vmax:
+ result.fill(0)
+ else:
+ if clip:
+ mask = np.ma.getmask(result)
+ result = np.ma.array(np.clip(result.filled(vmax), vmin, vmax),
+ mask=mask)
+ resdat = result.data
+ resdat -= vmin
+ resdat /= (vmax - vmin)
+ resdat[resdat > 0] = np.power(resdat[resdat > 0], gamma)
+
+ result = np.ma.array(resdat, mask=result.mask, copy=False)
+ if is_scalar:
+ result = result[0]
+ return result
+
+ def inverse(self, value):
+ if not self.scaled():
+ raise ValueError("Not invertible until scaled")
+
+ result, is_scalar = self.process_value(value)
+
+ gamma = self.gamma
+ vmin, vmax = self.vmin, self.vmax
+
+ resdat = result.data
+ resdat[resdat > 0] = np.power(resdat[resdat > 0], 1 / gamma)
+ resdat *= (vmax - vmin)
+ resdat += vmin
+
+ result = np.ma.array(resdat, mask=result.mask, copy=False)
+ if is_scalar:
+ result = result[0]
+ return result
+
+
+class BoundaryNorm(Normalize):
+ """
+ Generate a colormap index based on discrete intervals.
+
+ Unlike `Normalize` or `LogNorm`, `BoundaryNorm` maps values to integers
+ instead of to the interval 0-1.
+ """
+
+ # Mapping to the 0-1 interval could have been done via piece-wise linear
+ # interpolation, but using integers seems simpler, and reduces the number
+ # of conversions back and forth between int and float.
+
+ def __init__(self, boundaries, ncolors, clip=False, *, extend='neither'):
+ """
+ Parameters
+ ----------
+ boundaries : array-like
+ Monotonically increasing sequence of at least 2 bin edges: data
+ falling in the n-th bin will be mapped to the n-th color.
+
+ ncolors : int
+ Number of colors in the colormap to be used.
+
+ clip : bool, optional
+ If clip is ``True``, out of range values are mapped to 0 if they
+ are below ``boundaries[0]`` or mapped to ``ncolors - 1`` if they
+ are above ``boundaries[-1]``.
+
+ If clip is ``False``, out of range values are mapped to -1 if
+ they are below ``boundaries[0]`` or mapped to *ncolors* if they are
+ above ``boundaries[-1]``. These are then converted to valid indices
+ by `Colormap.__call__`.
+
+ extend : {'neither', 'both', 'min', 'max'}, default: 'neither'
+ Extend the number of bins to include one or both of the
+ regions beyond the boundaries. For example, if ``extend``
+ is 'min', then the color to which the region between the first
+ pair of boundaries is mapped will be distinct from the first
+ color in the colormap, and by default a
+ `~matplotlib.colorbar.Colorbar` will be drawn with
+ the triangle extension on the left or lower end.
+
+ Notes
+ -----
+ If there are fewer bins (including extensions) than colors, then the
+ color index is chosen by linearly interpolating the ``[0, nbins - 1]``
+ range onto the ``[0, ncolors - 1]`` range, effectively skipping some
+ colors in the middle of the colormap.
+ """
+ if clip and extend != 'neither':
+ raise ValueError("'clip=True' is not compatible with 'extend'")
+ super().__init__(vmin=boundaries[0], vmax=boundaries[-1], clip=clip)
+ self.boundaries = np.asarray(boundaries)
+ self.N = len(self.boundaries)
+ if self.N < 2:
+ raise ValueError("You must provide at least 2 boundaries "
+ f"(1 region) but you passed in {boundaries!r}")
+ self.Ncmap = ncolors
+ self.extend = extend
+
+ self._scale = None # don't use the default scale.
+
+ self._n_regions = self.N - 1 # number of colors needed
+ self._offset = 0
+ if extend in ('min', 'both'):
+ self._n_regions += 1
+ self._offset = 1
+ if extend in ('max', 'both'):
+ self._n_regions += 1
+ if self._n_regions > self.Ncmap:
+ raise ValueError(f"There are {self._n_regions} color bins "
+ "including extensions, but ncolors = "
+ f"{ncolors}; ncolors must equal or exceed the "
+ "number of bins")
+
+ def __call__(self, value, clip=None):
+ """
+ This method behaves similarly to `.Normalize.__call__`, except that it
+ returns integers or arrays of int16.
+ """
+ if clip is None:
+ clip = self.clip
+
+ xx, is_scalar = self.process_value(value)
+ mask = np.ma.getmaskarray(xx)
+ # Fill masked values a value above the upper boundary
+ xx = np.atleast_1d(xx.filled(self.vmax + 1))
+ if clip:
+ np.clip(xx, self.vmin, self.vmax, out=xx)
+ max_col = self.Ncmap - 1
+ else:
+ max_col = self.Ncmap
+ # this gives us the bins in the lookup table in the range
+ # [0, _n_regions - 1] (the offset is set in the init)
+ iret = np.digitize(xx, self.boundaries) - 1 + self._offset
+ # if we have more colors than regions, stretch the region
+ # index computed above to full range of the color bins. This
+ # will make use of the full range (but skip some of the colors
+ # in the middle) such that the first region is mapped to the
+ # first color and the last region is mapped to the last color.
+ if self.Ncmap > self._n_regions:
+ if self._n_regions == 1:
+ # special case the 1 region case, pick the middle color
+ iret[iret == 0] = (self.Ncmap - 1) // 2
+ else:
+ # otherwise linearly remap the values from the region index
+ # to the color index spaces
+ iret = (self.Ncmap - 1) / (self._n_regions - 1) * iret
+ # cast to 16bit integers in all cases
+ iret = iret.astype(np.int16)
+ iret[xx < self.vmin] = -1
+ iret[xx >= self.vmax] = max_col
+ ret = np.ma.array(iret, mask=mask)
+ if is_scalar:
+ ret = int(ret[0]) # assume python scalar
+ return ret
+
+ def inverse(self, value):
+ """
+ Raises
+ ------
+ ValueError
+ BoundaryNorm is not invertible, so calling this method will always
+ raise an error
+ """
+ raise ValueError("BoundaryNorm is not invertible")
+
+
+class NoNorm(Normalize):
+ """
+ Dummy replacement for `Normalize`, for the case where we want to use
+ indices directly in a `~matplotlib.cm.ScalarMappable`.
+ """
+ def __call__(self, value, clip=None):
+ if np.iterable(value):
+ return np.ma.array(value)
+ return value
+
+ def inverse(self, value):
+ if np.iterable(value):
+ return np.ma.array(value)
+ return value
+
+
+def rgb_to_hsv(arr):
+ """
+ Convert an array of float RGB values (in the range [0, 1]) to HSV values.
+
+ Parameters
+ ----------
+ arr : (..., 3) array-like
+ All values must be in the range [0, 1]
+
+ Returns
+ -------
+ (..., 3) `~numpy.ndarray`
+ Colors converted to HSV values in range [0, 1]
+ """
+ arr = np.asarray(arr)
+
+ # check length of the last dimension, should be _some_ sort of rgb
+ if arr.shape[-1] != 3:
+ raise ValueError("Last dimension of input array must be 3; "
+ f"shape {arr.shape} was found.")
+
+ in_shape = arr.shape
+ arr = np.array(
+ arr, copy=False,
+ dtype=np.promote_types(arr.dtype, np.float32), # Don't work on ints.
+ ndmin=2, # In case input was 1D.
+ )
+
+ out = np.zeros_like(arr)
+ arr_max = arr.max(-1)
+ # Check if input is in the expected range
+ if np.any(arr_max > 1):
+ raise ValueError(
+ "Input array must be in the range [0, 1]. "
+ f"Found a maximum value of {arr_max.max()}"
+ )
+
+ if arr.min() < 0:
+ raise ValueError(
+ "Input array must be in the range [0, 1]. "
+ f"Found a minimum value of {arr.min()}"
+ )
+
+ ipos = arr_max > 0
+ delta = np.ptp(arr, -1)
+ s = np.zeros_like(delta)
+ s[ipos] = delta[ipos] / arr_max[ipos]
+ ipos = delta > 0
+ # red is max
+ idx = (arr[..., 0] == arr_max) & ipos
+ out[idx, 0] = (arr[idx, 1] - arr[idx, 2]) / delta[idx]
+ # green is max
+ idx = (arr[..., 1] == arr_max) & ipos
+ out[idx, 0] = 2. + (arr[idx, 2] - arr[idx, 0]) / delta[idx]
+ # blue is max
+ idx = (arr[..., 2] == arr_max) & ipos
+ out[idx, 0] = 4. + (arr[idx, 0] - arr[idx, 1]) / delta[idx]
+
+ out[..., 0] = (out[..., 0] / 6.0) % 1.0
+ out[..., 1] = s
+ out[..., 2] = arr_max
+
+ return out.reshape(in_shape)
+
+
+def hsv_to_rgb(hsv):
+ """
+ Convert HSV values to RGB.
+
+ Parameters
+ ----------
+ hsv : (..., 3) array-like
+ All values assumed to be in range [0, 1]
+
+ Returns
+ -------
+ (..., 3) `~numpy.ndarray`
+ Colors converted to RGB values in range [0, 1]
+ """
+ hsv = np.asarray(hsv)
+
+ # check length of the last dimension, should be _some_ sort of rgb
+ if hsv.shape[-1] != 3:
+ raise ValueError("Last dimension of input array must be 3; "
+ f"shape {hsv.shape} was found.")
+
+ in_shape = hsv.shape
+ hsv = np.array(
+ hsv, copy=False,
+ dtype=np.promote_types(hsv.dtype, np.float32), # Don't work on ints.
+ ndmin=2, # In case input was 1D.
+ )
+
+ h = hsv[..., 0]
+ s = hsv[..., 1]
+ v = hsv[..., 2]
+
+ r = np.empty_like(h)
+ g = np.empty_like(h)
+ b = np.empty_like(h)
+
+ i = (h * 6.0).astype(int)
+ f = (h * 6.0) - i
+ p = v * (1.0 - s)
+ q = v * (1.0 - s * f)
+ t = v * (1.0 - s * (1.0 - f))
+
+ idx = i % 6 == 0
+ r[idx] = v[idx]
+ g[idx] = t[idx]
+ b[idx] = p[idx]
+
+ idx = i == 1
+ r[idx] = q[idx]
+ g[idx] = v[idx]
+ b[idx] = p[idx]
+
+ idx = i == 2
+ r[idx] = p[idx]
+ g[idx] = v[idx]
+ b[idx] = t[idx]
+
+ idx = i == 3
+ r[idx] = p[idx]
+ g[idx] = q[idx]
+ b[idx] = v[idx]
+
+ idx = i == 4
+ r[idx] = t[idx]
+ g[idx] = p[idx]
+ b[idx] = v[idx]
+
+ idx = i == 5
+ r[idx] = v[idx]
+ g[idx] = p[idx]
+ b[idx] = q[idx]
+
+ idx = s == 0
+ r[idx] = v[idx]
+ g[idx] = v[idx]
+ b[idx] = v[idx]
+
+ rgb = np.stack([r, g, b], axis=-1)
+
+ return rgb.reshape(in_shape)
+
+
+def _vector_magnitude(arr):
+ # things that don't work here:
+ # * np.linalg.norm: drops mask from ma.array
+ # * np.sum: drops mask from ma.array unless entire vector is masked
+ sum_sq = 0
+ for i in range(arr.shape[-1]):
+ sum_sq += arr[..., i, np.newaxis] ** 2
+ return np.sqrt(sum_sq)
+
+
+class LightSource:
+ """
+ Create a light source coming from the specified azimuth and elevation.
+ Angles are in degrees, with the azimuth measured
+ clockwise from north and elevation up from the zero plane of the surface.
+
+ `shade` is used to produce "shaded" RGB values for a data array.
+ `shade_rgb` can be used to combine an RGB image with an elevation map.
+ `hillshade` produces an illumination map of a surface.
+ """
+
+ def __init__(self, azdeg=315, altdeg=45, hsv_min_val=0, hsv_max_val=1,
+ hsv_min_sat=1, hsv_max_sat=0):
+ """
+ Specify the azimuth (measured clockwise from south) and altitude
+ (measured up from the plane of the surface) of the light source
+ in degrees.
+
+ Parameters
+ ----------
+ azdeg : float, default: 315 degrees (from the northwest)
+ The azimuth (0-360, degrees clockwise from North) of the light
+ source.
+ altdeg : float, default: 45 degrees
+ The altitude (0-90, degrees up from horizontal) of the light
+ source.
+ hsv_min_val : number, default: 0
+ The minimum value ("v" in "hsv") that the *intensity* map can shift the
+ output image to.
+ hsv_max_val : number, default: 1
+ The maximum value ("v" in "hsv") that the *intensity* map can shift the
+ output image to.
+ hsv_min_sat : number, default: 1
+ The minimum saturation value that the *intensity* map can shift the output
+ image to.
+ hsv_max_sat : number, default: 0
+ The maximum saturation value that the *intensity* map can shift the output
+ image to.
+
+ Notes
+ -----
+ For backwards compatibility, the parameters *hsv_min_val*,
+ *hsv_max_val*, *hsv_min_sat*, and *hsv_max_sat* may be supplied at
+ initialization as well. However, these parameters will only be used if
+ "blend_mode='hsv'" is passed into `shade` or `shade_rgb`.
+ See the documentation for `blend_hsv` for more details.
+ """
+ self.azdeg = azdeg
+ self.altdeg = altdeg
+ self.hsv_min_val = hsv_min_val
+ self.hsv_max_val = hsv_max_val
+ self.hsv_min_sat = hsv_min_sat
+ self.hsv_max_sat = hsv_max_sat
+
+ @property
+ def direction(self):
+ """The unit vector direction towards the light source."""
+ # Azimuth is in degrees clockwise from North. Convert to radians
+ # counterclockwise from East (mathematical notation).
+ az = np.radians(90 - self.azdeg)
+ alt = np.radians(self.altdeg)
+ return np.array([
+ np.cos(az) * np.cos(alt),
+ np.sin(az) * np.cos(alt),
+ np.sin(alt)
+ ])
+
+ def hillshade(self, elevation, vert_exag=1, dx=1, dy=1, fraction=1.):
+ """
+ Calculate the illumination intensity for a surface using the defined
+ azimuth and elevation for the light source.
+
+ This computes the normal vectors for the surface, and then passes them
+ on to `shade_normals`
+
+ Parameters
+ ----------
+ elevation : 2D array-like
+ The height values used to generate an illumination map
+ vert_exag : number, optional
+ The amount to exaggerate the elevation values by when calculating
+ illumination. This can be used either to correct for differences in
+ units between the x-y coordinate system and the elevation
+ coordinate system (e.g. decimal degrees vs. meters) or to
+ exaggerate or de-emphasize topographic effects.
+ dx : number, optional
+ The x-spacing (columns) of the input *elevation* grid.
+ dy : number, optional
+ The y-spacing (rows) of the input *elevation* grid.
+ fraction : number, optional
+ Increases or decreases the contrast of the hillshade. Values
+ greater than one will cause intermediate values to move closer to
+ full illumination or shadow (and clipping any values that move
+ beyond 0 or 1). Note that this is not visually or mathematically
+ the same as vertical exaggeration.
+
+ Returns
+ -------
+ `~numpy.ndarray`
+ A 2D array of illumination values between 0-1, where 0 is
+ completely in shadow and 1 is completely illuminated.
+ """
+
+ # Because most image and raster GIS data has the first row in the array
+ # as the "top" of the image, dy is implicitly negative. This is
+ # consistent to what `imshow` assumes, as well.
+ dy = -dy
+
+ # compute the normal vectors from the partial derivatives
+ e_dy, e_dx = np.gradient(vert_exag * elevation, dy, dx)
+
+ # .view is to keep subclasses
+ normal = np.empty(elevation.shape + (3,)).view(type(elevation))
+ normal[..., 0] = -e_dx
+ normal[..., 1] = -e_dy
+ normal[..., 2] = 1
+ normal /= _vector_magnitude(normal)
+
+ return self.shade_normals(normal, fraction)
+
+ def shade_normals(self, normals, fraction=1.):
+ """
+ Calculate the illumination intensity for the normal vectors of a
+ surface using the defined azimuth and elevation for the light source.
+
+ Imagine an artificial sun placed at infinity in some azimuth and
+ elevation position illuminating our surface. The parts of the surface
+ that slope toward the sun should brighten while those sides facing away
+ should become darker.
+
+ Parameters
+ ----------
+ fraction : number, optional
+ Increases or decreases the contrast of the hillshade. Values
+ greater than one will cause intermediate values to move closer to
+ full illumination or shadow (and clipping any values that move
+ beyond 0 or 1). Note that this is not visually or mathematically
+ the same as vertical exaggeration.
+
+ Returns
+ -------
+ `~numpy.ndarray`
+ A 2D array of illumination values between 0-1, where 0 is
+ completely in shadow and 1 is completely illuminated.
+ """
+
+ intensity = normals.dot(self.direction)
+
+ # Apply contrast stretch
+ imin, imax = intensity.min(), intensity.max()
+ intensity *= fraction
+
+ # Rescale to 0-1, keeping range before contrast stretch
+ # If constant slope, keep relative scaling (i.e. flat should be 0.5,
+ # fully occluded 0, etc.)
+ if (imax - imin) > 1e-6:
+ # Strictly speaking, this is incorrect. Negative values should be
+ # clipped to 0 because they're fully occluded. However, rescaling
+ # in this manner is consistent with the previous implementation and
+ # visually appears better than a "hard" clip.
+ intensity -= imin
+ intensity /= (imax - imin)
+ intensity = np.clip(intensity, 0, 1)
+
+ return intensity
+
+ def shade(self, data, cmap, norm=None, blend_mode='overlay', vmin=None,
+ vmax=None, vert_exag=1, dx=1, dy=1, fraction=1, **kwargs):
+ """
+ Combine colormapped data values with an illumination intensity map
+ (a.k.a. "hillshade") of the values.
+
+ Parameters
+ ----------
+ data : 2D array-like
+ The height values used to generate a shaded map.
+ cmap : `~matplotlib.colors.Colormap`
+ The colormap used to color the *data* array. Note that this must be
+ a `~matplotlib.colors.Colormap` instance. For example, rather than
+ passing in ``cmap='gist_earth'``, use
+ ``cmap=plt.get_cmap('gist_earth')`` instead.
+ norm : `~matplotlib.colors.Normalize` instance, optional
+ The normalization used to scale values before colormapping. If
+ None, the input will be linearly scaled between its min and max.
+ blend_mode : {'hsv', 'overlay', 'soft'} or callable, optional
+ The type of blending used to combine the colormapped data
+ values with the illumination intensity. Default is
+ "overlay". Note that for most topographic surfaces,
+ "overlay" or "soft" appear more visually realistic. If a
+ user-defined function is supplied, it is expected to
+ combine an (M, N, 3) RGB array of floats (ranging 0 to 1) with
+ an (M, N, 1) hillshade array (also 0 to 1). (Call signature
+ ``func(rgb, illum, **kwargs)``) Additional kwargs supplied
+ to this function will be passed on to the *blend_mode*
+ function.
+ vmin : float or None, optional
+ The minimum value used in colormapping *data*. If *None* the
+ minimum value in *data* is used. If *norm* is specified, then this
+ argument will be ignored.
+ vmax : float or None, optional
+ The maximum value used in colormapping *data*. If *None* the
+ maximum value in *data* is used. If *norm* is specified, then this
+ argument will be ignored.
+ vert_exag : number, optional
+ The amount to exaggerate the elevation values by when calculating
+ illumination. This can be used either to correct for differences in
+ units between the x-y coordinate system and the elevation
+ coordinate system (e.g. decimal degrees vs. meters) or to
+ exaggerate or de-emphasize topography.
+ dx : number, optional
+ The x-spacing (columns) of the input *elevation* grid.
+ dy : number, optional
+ The y-spacing (rows) of the input *elevation* grid.
+ fraction : number, optional
+ Increases or decreases the contrast of the hillshade. Values
+ greater than one will cause intermediate values to move closer to
+ full illumination or shadow (and clipping any values that move
+ beyond 0 or 1). Note that this is not visually or mathematically
+ the same as vertical exaggeration.
+ **kwargs
+ Additional kwargs are passed on to the *blend_mode* function.
+
+ Returns
+ -------
+ `~numpy.ndarray`
+ An (M, N, 4) array of floats ranging between 0-1.
+ """
+ if vmin is None:
+ vmin = data.min()
+ if vmax is None:
+ vmax = data.max()
+ if norm is None:
+ norm = Normalize(vmin=vmin, vmax=vmax)
+
+ rgb0 = cmap(norm(data))
+ rgb1 = self.shade_rgb(rgb0, elevation=data, blend_mode=blend_mode,
+ vert_exag=vert_exag, dx=dx, dy=dy,
+ fraction=fraction, **kwargs)
+ # Don't overwrite the alpha channel, if present.
+ rgb0[..., :3] = rgb1[..., :3]
+ return rgb0
+
+ def shade_rgb(self, rgb, elevation, fraction=1., blend_mode='hsv',
+ vert_exag=1, dx=1, dy=1, **kwargs):
+ """
+ Use this light source to adjust the colors of the *rgb* input array to
+ give the impression of a shaded relief map with the given *elevation*.
+
+ Parameters
+ ----------
+ rgb : array-like
+ An (M, N, 3) RGB array, assumed to be in the range of 0 to 1.
+ elevation : array-like
+ An (M, N) array of the height values used to generate a shaded map.
+ fraction : number
+ Increases or decreases the contrast of the hillshade. Values
+ greater than one will cause intermediate values to move closer to
+ full illumination or shadow (and clipping any values that move
+ beyond 0 or 1). Note that this is not visually or mathematically
+ the same as vertical exaggeration.
+ blend_mode : {'hsv', 'overlay', 'soft'} or callable, optional
+ The type of blending used to combine the colormapped data values
+ with the illumination intensity. For backwards compatibility, this
+ defaults to "hsv". Note that for most topographic surfaces,
+ "overlay" or "soft" appear more visually realistic. If a
+ user-defined function is supplied, it is expected to combine an
+ (M, N, 3) RGB array of floats (ranging 0 to 1) with an (M, N, 1)
+ hillshade array (also 0 to 1). (Call signature
+ ``func(rgb, illum, **kwargs)``)
+ Additional kwargs supplied to this function will be passed on to
+ the *blend_mode* function.
+ vert_exag : number, optional
+ The amount to exaggerate the elevation values by when calculating
+ illumination. This can be used either to correct for differences in
+ units between the x-y coordinate system and the elevation
+ coordinate system (e.g. decimal degrees vs. meters) or to
+ exaggerate or de-emphasize topography.
+ dx : number, optional
+ The x-spacing (columns) of the input *elevation* grid.
+ dy : number, optional
+ The y-spacing (rows) of the input *elevation* grid.
+ **kwargs
+ Additional kwargs are passed on to the *blend_mode* function.
+
+ Returns
+ -------
+ `~numpy.ndarray`
+ An (m, n, 3) array of floats ranging between 0-1.
+ """
+ # Calculate the "hillshade" intensity.
+ intensity = self.hillshade(elevation, vert_exag, dx, dy, fraction)
+ intensity = intensity[..., np.newaxis]
+
+ # Blend the hillshade and rgb data using the specified mode
+ lookup = {
+ 'hsv': self.blend_hsv,
+ 'soft': self.blend_soft_light,
+ 'overlay': self.blend_overlay,
+ }
+ if blend_mode in lookup:
+ blend = lookup[blend_mode](rgb, intensity, **kwargs)
+ else:
+ try:
+ blend = blend_mode(rgb, intensity, **kwargs)
+ except TypeError as err:
+ raise ValueError('"blend_mode" must be callable or one of '
+ f'{lookup.keys}') from err
+
+ # Only apply result where hillshade intensity isn't masked
+ if np.ma.is_masked(intensity):
+ mask = intensity.mask[..., 0]
+ for i in range(3):
+ blend[..., i][mask] = rgb[..., i][mask]
+
+ return blend
+
+ def blend_hsv(self, rgb, intensity, hsv_max_sat=None, hsv_max_val=None,
+ hsv_min_val=None, hsv_min_sat=None):
+ """
+ Take the input data array, convert to HSV values in the given colormap,
+ then adjust those color values to give the impression of a shaded
+ relief map with a specified light source. RGBA values are returned,
+ which can then be used to plot the shaded image with imshow.
+
+ The color of the resulting image will be darkened by moving the (s, v)
+ values (in HSV colorspace) toward (hsv_min_sat, hsv_min_val) in the
+ shaded regions, or lightened by sliding (s, v) toward (hsv_max_sat,
+ hsv_max_val) in regions that are illuminated. The default extremes are
+ chose so that completely shaded points are nearly black (s = 1, v = 0)
+ and completely illuminated points are nearly white (s = 0, v = 1).
+
+ Parameters
+ ----------
+ rgb : `~numpy.ndarray`
+ An (M, N, 3) RGB array of floats ranging from 0 to 1 (color image).
+ intensity : `~numpy.ndarray`
+ An (M, N, 1) array of floats ranging from 0 to 1 (grayscale image).
+ hsv_max_sat : number, optional
+ The maximum saturation value that the *intensity* map can shift the output
+ image to. If not provided, use the value provided upon initialization.
+ hsv_min_sat : number, optional
+ The minimum saturation value that the *intensity* map can shift the output
+ image to. If not provided, use the value provided upon initialization.
+ hsv_max_val : number, optional
+ The maximum value ("v" in "hsv") that the *intensity* map can shift the
+ output image to. If not provided, use the value provided upon
+ initialization.
+ hsv_min_val : number, optional
+ The minimum value ("v" in "hsv") that the *intensity* map can shift the
+ output image to. If not provided, use the value provided upon
+ initialization.
+
+ Returns
+ -------
+ `~numpy.ndarray`
+ An (M, N, 3) RGB array representing the combined images.
+ """
+ # Backward compatibility...
+ if hsv_max_sat is None:
+ hsv_max_sat = self.hsv_max_sat
+ if hsv_max_val is None:
+ hsv_max_val = self.hsv_max_val
+ if hsv_min_sat is None:
+ hsv_min_sat = self.hsv_min_sat
+ if hsv_min_val is None:
+ hsv_min_val = self.hsv_min_val
+
+ # Expects a 2D intensity array scaled between -1 to 1...
+ intensity = intensity[..., 0]
+ intensity = 2 * intensity - 1
+
+ # Convert to rgb, then rgb to hsv
+ hsv = rgb_to_hsv(rgb[:, :, 0:3])
+ hue, sat, val = np.moveaxis(hsv, -1, 0)
+
+ # Modify hsv values (in place) to simulate illumination.
+ # putmask(A, mask, B) <=> A[mask] = B[mask]
+ np.putmask(sat, (np.abs(sat) > 1.e-10) & (intensity > 0),
+ (1 - intensity) * sat + intensity * hsv_max_sat)
+ np.putmask(sat, (np.abs(sat) > 1.e-10) & (intensity < 0),
+ (1 + intensity) * sat - intensity * hsv_min_sat)
+ np.putmask(val, intensity > 0,
+ (1 - intensity) * val + intensity * hsv_max_val)
+ np.putmask(val, intensity < 0,
+ (1 + intensity) * val - intensity * hsv_min_val)
+ np.clip(hsv[:, :, 1:], 0, 1, out=hsv[:, :, 1:])
+
+ # Convert modified hsv back to rgb.
+ return hsv_to_rgb(hsv)
+
+ def blend_soft_light(self, rgb, intensity):
+ """
+ Combine an RGB image with an intensity map using "soft light" blending,
+ using the "pegtop" formula.
+
+ Parameters
+ ----------
+ rgb : `~numpy.ndarray`
+ An (M, N, 3) RGB array of floats ranging from 0 to 1 (color image).
+ intensity : `~numpy.ndarray`
+ An (M, N, 1) array of floats ranging from 0 to 1 (grayscale image).
+
+ Returns
+ -------
+ `~numpy.ndarray`
+ An (M, N, 3) RGB array representing the combined images.
+ """
+ return 2 * intensity * rgb + (1 - 2 * intensity) * rgb**2
+
+ def blend_overlay(self, rgb, intensity):
+ """
+ Combine an RGB image with an intensity map using "overlay" blending.
+
+ Parameters
+ ----------
+ rgb : `~numpy.ndarray`
+ An (M, N, 3) RGB array of floats ranging from 0 to 1 (color image).
+ intensity : `~numpy.ndarray`
+ An (M, N, 1) array of floats ranging from 0 to 1 (grayscale image).
+
+ Returns
+ -------
+ ndarray
+ An (M, N, 3) RGB array representing the combined images.
+ """
+ low = 2 * intensity * rgb
+ high = 1 - 2 * (1 - intensity) * (1 - rgb)
+ return np.where(rgb <= 0.5, low, high)
+
+
+def from_levels_and_colors(levels, colors, extend='neither'):
+ """
+ A helper routine to generate a cmap and a norm instance which
+ behave similar to contourf's levels and colors arguments.
+
+ Parameters
+ ----------
+ levels : sequence of numbers
+ The quantization levels used to construct the `BoundaryNorm`.
+ Value ``v`` is quantized to level ``i`` if ``lev[i] <= v < lev[i+1]``.
+ colors : sequence of colors
+ The fill color to use for each level. If *extend* is "neither" there
+ must be ``n_level - 1`` colors. For an *extend* of "min" or "max" add
+ one extra color, and for an *extend* of "both" add two colors.
+ extend : {'neither', 'min', 'max', 'both'}, optional
+ The behaviour when a value falls out of range of the given levels.
+ See `~.Axes.contourf` for details.
+
+ Returns
+ -------
+ cmap : `~matplotlib.colors.Colormap`
+ norm : `~matplotlib.colors.Normalize`
+ """
+ slice_map = {
+ 'both': slice(1, -1),
+ 'min': slice(1, None),
+ 'max': slice(0, -1),
+ 'neither': slice(0, None),
+ }
+ _api.check_in_list(slice_map, extend=extend)
+ color_slice = slice_map[extend]
+
+ n_data_colors = len(levels) - 1
+ n_expected = n_data_colors + color_slice.start - (color_slice.stop or 0)
+ if len(colors) != n_expected:
+ raise ValueError(
+ f'With extend == {extend!r} and {len(levels)} levels, '
+ f'expected {n_expected} colors, but got {len(colors)}')
+
+ cmap = ListedColormap(colors[color_slice], N=n_data_colors)
+
+ if extend in ['min', 'both']:
+ cmap.set_under(colors[0])
+ else:
+ cmap.set_under('none')
+
+ if extend in ['max', 'both']:
+ cmap.set_over(colors[-1])
+ else:
+ cmap.set_over('none')
+
+ cmap.colorbar_extend = extend
+
+ norm = BoundaryNorm(levels, ncolors=n_data_colors)
+ return cmap, norm
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/colors.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/colors.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..6941e3d5d176c39525c27e9a60d6926a18e31e8b
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/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/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/container.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/container.py
new file mode 100644
index 0000000000000000000000000000000000000000..b6dd43724f34b219a7d8864542af4dbec81d89ff
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/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/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/container.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/container.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..c66e7ba4b4c32fc5e27fe06761efb6a3c7f86172
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/container.pyi
@@ -0,0 +1,56 @@
+from matplotlib.artist import Artist
+from matplotlib.lines import Line2D
+from matplotlib.collections import LineCollection
+from matplotlib.patches import Rectangle
+
+from collections.abc import Callable
+from typing import Any, Literal
+from numpy.typing import ArrayLike
+
+class Container(tuple):
+ def __new__(cls, *args, **kwargs): ...
+ def __init__(self, kl, label: Any | None = ...) -> None: ...
+ def remove(self) -> None: ...
+ def get_children(self) -> list[Artist]: ...
+ def get_label(self) -> str | None: ...
+ def set_label(self, s: Any) -> None: ...
+ def add_callback(self, func: Callable[[Artist], Any]) -> int: ...
+ def remove_callback(self, oid: int) -> None: ...
+ def pchanged(self) -> None: ...
+
+class BarContainer(Container):
+ patches: list[Rectangle]
+ errorbar: None | ErrorbarContainer
+ datavalues: None | ArrayLike
+ orientation: None | Literal["vertical", "horizontal"]
+ def __init__(
+ self,
+ patches: list[Rectangle],
+ errorbar: ErrorbarContainer | None = ...,
+ *,
+ datavalues: ArrayLike | None = ...,
+ orientation: Literal["vertical", "horizontal"] | None = ...,
+ **kwargs
+ ) -> None: ...
+
+class ErrorbarContainer(Container):
+ lines: tuple[Line2D, tuple[Line2D, ...], tuple[LineCollection, ...]]
+ has_xerr: bool
+ has_yerr: bool
+ def __init__(
+ self,
+ lines: tuple[Line2D, tuple[Line2D, ...], tuple[LineCollection, ...]],
+ has_xerr: bool = ...,
+ has_yerr: bool = ...,
+ **kwargs
+ ) -> None: ...
+
+class StemContainer(Container):
+ markerline: Line2D
+ stemlines: LineCollection
+ baseline: Line2D
+ def __init__(
+ self,
+ markerline_stemlines_baseline: tuple[Line2D, LineCollection, Line2D],
+ **kwargs
+ ) -> None: ...
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/contour.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/contour.py
new file mode 100644
index 0000000000000000000000000000000000000000..f7318d57812161ab164e3d3e3a62ab13cf020c2c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/contour.py
@@ -0,0 +1,1702 @@
+"""
+Classes to support contour plotting and labelling for the Axes class.
+"""
+
+from contextlib import ExitStack
+import functools
+import math
+from numbers import Integral
+
+import numpy as np
+from numpy import ma
+
+import matplotlib as mpl
+from matplotlib import _api, _docstring
+from matplotlib.backend_bases import MouseButton
+from matplotlib.lines import Line2D
+from matplotlib.path import Path
+from matplotlib.text import Text
+import matplotlib.ticker as ticker
+import matplotlib.cm as cm
+import matplotlib.colors as mcolors
+import matplotlib.collections as mcoll
+import matplotlib.font_manager as font_manager
+import matplotlib.cbook as cbook
+import matplotlib.patches as mpatches
+import matplotlib.transforms as mtransforms
+
+
+def _contour_labeler_event_handler(cs, inline, inline_spacing, event):
+ canvas = cs.axes.get_figure(root=True).canvas
+ 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 == MouseButton.MIDDLE
+ or is_key and event.key in ["escape", "enter"]):
+ canvas.stop_event_loop()
+ # Pop last click.
+ elif (is_button and event.button == MouseButton.RIGHT
+ or is_key and event.key in ["backspace", "delete"]):
+ # Unfortunately, if one is doing inline labels, then there is currently
+ # no way to fix the broken contour - once humpty-dumpty is broken, he
+ # can't be put back together. In inline mode, this does nothing.
+ if not inline:
+ cs.pop_label()
+ canvas.draw()
+ # Add new click.
+ elif (is_button and event.button == MouseButton.LEFT
+ # On macOS/gtk, some keys return None.
+ or is_key and event.key is not None):
+ if cs.axes.contains(event)[0]:
+ cs.add_label_near(event.x, event.y, transform=False,
+ inline=inline, inline_spacing=inline_spacing)
+ canvas.draw()
+
+
+class ContourLabeler:
+ """Mixin to provide labelling capability to `.ContourSet`."""
+
+ def clabel(self, levels=None, *,
+ fontsize=None, inline=True, inline_spacing=5, fmt=None,
+ colors=None, use_clabeltext=False, manual=False,
+ rightside_up=True, zorder=None):
+ """
+ Label a contour plot.
+
+ Adds labels to line contours in this `.ContourSet` (which inherits from
+ this mixin class).
+
+ Parameters
+ ----------
+ levels : array-like, optional
+ A list of level values, that should be labeled. The list must be
+ a subset of ``cs.levels``. If not given, all levels are labeled.
+
+ fontsize : str or float, default: :rc:`font.size`
+ Size in points or relative size e.g., 'smaller', 'x-large'.
+ See `.Text.set_size` for accepted string values.
+
+ colors : :mpltype:`color` or colors or None, default: None
+ The label colors:
+
+ - If *None*, the color of each label matches the color of
+ the corresponding contour.
+
+ - If one string color, e.g., *colors* = 'r' or *colors* =
+ 'red', all labels will be plotted in this color.
+
+ - If a tuple of colors (string, float, RGB, etc), different labels
+ will be plotted in different colors in the order specified.
+
+ inline : bool, default: True
+ If ``True`` the underlying contour is removed where the label is
+ placed.
+
+ inline_spacing : float, default: 5
+ Space in pixels to leave on each side of label when placing inline.
+
+ This spacing will be exact for labels at locations where the
+ contour is straight, less so for labels on curved contours.
+
+ fmt : `.Formatter` or str or callable or dict, optional
+ How the levels are formatted:
+
+ - If a `.Formatter`, it is used to format all levels at once, using
+ its `.Formatter.format_ticks` method.
+ - If a str, it is interpreted as a %-style format string.
+ - If a callable, it is called with one level at a time and should
+ return the corresponding label.
+ - If a dict, it should directly map levels to labels.
+
+ The default is to use a standard `.ScalarFormatter`.
+
+ manual : bool or iterable, default: False
+ If ``True``, contour labels will be placed manually using
+ mouse clicks. Click the first button near a contour to
+ add a label, click the second button (or potentially both
+ mouse buttons at once) to finish adding labels. The third
+ button can be used to remove the last label added, but
+ only if labels are not inline. Alternatively, the keyboard
+ can be used to select label locations (enter to end label
+ placement, delete or backspace act like the third mouse button,
+ and any other key will select a label location).
+
+ *manual* can also be an iterable object of (x, y) tuples.
+ Contour labels will be created as if mouse is clicked at each
+ (x, y) position.
+
+ rightside_up : bool, default: True
+ If ``True``, label rotations will always be plus
+ or minus 90 degrees from level.
+
+ use_clabeltext : bool, default: False
+ If ``True``, use `.Text.set_transform_rotates_text` to ensure that
+ label rotation is updated whenever the Axes aspect changes.
+
+ zorder : float or None, default: ``(2 + contour.get_zorder())``
+ zorder of the contour labels.
+
+ Returns
+ -------
+ labels
+ A list of `.Text` instances for the labels.
+ """
+
+ # Based on the input arguments, clabel() adds a list of "label
+ # specific" attributes to the ContourSet object. These attributes are
+ # all of the form label* and names should be fairly self explanatory.
+ #
+ # Once these attributes are set, clabel passes control to the labels()
+ # method (for automatic label placement) or blocking_input_loop and
+ # _contour_labeler_event_handler (for manual label placement).
+
+ if fmt is None:
+ fmt = ticker.ScalarFormatter(useOffset=False)
+ fmt.create_dummy_axis()
+ self.labelFmt = fmt
+ self._use_clabeltext = use_clabeltext
+ self.labelManual = manual
+ self.rightside_up = rightside_up
+ self._clabel_zorder = 2 + self.get_zorder() if zorder is None else zorder
+
+ if levels is None:
+ levels = self.levels
+ indices = list(range(len(self.cvalues)))
+ else:
+ levlabs = list(levels)
+ indices, levels = [], []
+ for i, lev in enumerate(self.levels):
+ if lev in levlabs:
+ indices.append(i)
+ levels.append(lev)
+ if len(levels) < len(levlabs):
+ raise ValueError(f"Specified levels {levlabs} don't match "
+ f"available levels {self.levels}")
+ self.labelLevelList = levels
+ self.labelIndiceList = indices
+
+ self._label_font_props = font_manager.FontProperties(size=fontsize)
+
+ if colors is None:
+ self.labelMappable = self
+ self.labelCValueList = np.take(self.cvalues, self.labelIndiceList)
+ else:
+ cmap = mcolors.ListedColormap(colors, N=len(self.labelLevelList))
+ self.labelCValueList = list(range(len(self.labelLevelList)))
+ self.labelMappable = cm.ScalarMappable(cmap=cmap,
+ norm=mcolors.NoNorm())
+
+ self.labelXYs = []
+
+ if np.iterable(manual):
+ for x, y in manual:
+ self.add_label_near(x, y, inline, inline_spacing)
+ elif manual:
+ print('Select label locations manually using first mouse button.')
+ print('End manual selection with second mouse button.')
+ if not inline:
+ print('Remove last label by clicking third mouse button.')
+ mpl._blocking_input.blocking_input_loop(
+ self.axes.get_figure(root=True),
+ ["button_press_event", "key_press_event"],
+ timeout=-1, handler=functools.partial(
+ _contour_labeler_event_handler,
+ self, inline, inline_spacing))
+ else:
+ self.labels(inline, inline_spacing)
+
+ return cbook.silent_list('text.Text', self.labelTexts)
+
+ def print_label(self, linecontour, labelwidth):
+ """Return whether a contour is long enough to hold a label."""
+ return (len(linecontour) > 10 * labelwidth
+ or (len(linecontour)
+ and (np.ptp(linecontour, axis=0) > 1.2 * labelwidth).any()))
+
+ def too_close(self, x, y, lw):
+ """Return whether a label is already near this location."""
+ thresh = (1.2 * lw) ** 2
+ return any((x - loc[0]) ** 2 + (y - loc[1]) ** 2 < thresh
+ for loc in self.labelXYs)
+
+ def _get_nth_label_width(self, nth):
+ """Return the width of the *nth* label, in pixels."""
+ fig = self.axes.get_figure(root=False)
+ renderer = fig.get_figure(root=True)._get_renderer()
+ return (Text(0, 0,
+ self.get_text(self.labelLevelList[nth], self.labelFmt),
+ figure=fig, fontproperties=self._label_font_props)
+ .get_window_extent(renderer).width)
+
+ def get_text(self, lev, fmt):
+ """Get the text of the label."""
+ if isinstance(lev, str):
+ return lev
+ elif isinstance(fmt, dict):
+ return fmt.get(lev, '%1.3f')
+ elif callable(getattr(fmt, "format_ticks", None)):
+ return fmt.format_ticks([*self.labelLevelList, lev])[-1]
+ elif callable(fmt):
+ return fmt(lev)
+ else:
+ return fmt % lev
+
+ def locate_label(self, linecontour, labelwidth):
+ """
+ Find good place to draw a label (relatively flat part of the contour).
+ """
+ ctr_size = len(linecontour)
+ n_blocks = int(np.ceil(ctr_size / labelwidth)) if labelwidth > 1 else 1
+ block_size = ctr_size if n_blocks == 1 else int(labelwidth)
+ # Split contour into blocks of length ``block_size``, filling the last
+ # block by cycling the contour start (per `np.resize` semantics). (Due
+ # to cycling, the index returned is taken modulo ctr_size.)
+ xx = np.resize(linecontour[:, 0], (n_blocks, block_size))
+ yy = np.resize(linecontour[:, 1], (n_blocks, block_size))
+ yfirst = yy[:, :1]
+ ylast = yy[:, -1:]
+ xfirst = xx[:, :1]
+ xlast = xx[:, -1:]
+ s = (yfirst - yy) * (xlast - xfirst) - (xfirst - xx) * (ylast - yfirst)
+ l = np.hypot(xlast - xfirst, ylast - yfirst)
+ # Ignore warning that divide by zero throws, as this is a valid option
+ with np.errstate(divide='ignore', invalid='ignore'):
+ distances = (abs(s) / l).sum(axis=-1)
+ # Labels are drawn in the middle of the block (``hbsize``) where the
+ # contour is the closest (per ``distances``) to a straight line, but
+ # not `too_close()` to a preexisting label.
+ hbsize = block_size // 2
+ adist = np.argsort(distances)
+ # If all candidates are `too_close()`, go back to the straightest part
+ # (``adist[0]``).
+ for idx in np.append(adist, adist[0]):
+ x, y = xx[idx, hbsize], yy[idx, hbsize]
+ if not self.too_close(x, y, labelwidth):
+ break
+ return x, y, (idx * block_size + hbsize) % ctr_size
+
+ def _split_path_and_get_label_rotation(self, path, idx, screen_pos, lw, spacing=5):
+ """
+ Prepare for insertion of a label at index *idx* of *path*.
+
+ Parameters
+ ----------
+ path : Path
+ The path where the label will be inserted, in data space.
+ idx : int
+ The vertex index after which the label will be inserted.
+ screen_pos : (float, float)
+ The position where the label will be inserted, in screen space.
+ lw : float
+ The label width, in screen space.
+ spacing : float
+ Extra spacing around the label, in screen space.
+
+ Returns
+ -------
+ path : Path
+ The path, broken so that the label can be drawn over it.
+ angle : float
+ The rotation of the label.
+
+ Notes
+ -----
+ Both tasks are done together to avoid calculating path lengths multiple times,
+ which is relatively costly.
+
+ The method used here involves computing the path length along the contour in
+ pixel coordinates and then looking (label width / 2) away from central point to
+ determine rotation and then to break contour if desired. The extra spacing is
+ taken into account when breaking the path, but not when computing the angle.
+ """
+ xys = path.vertices
+ codes = path.codes
+
+ # Insert a vertex at idx/pos (converting back to data space), if there isn't yet
+ # a vertex there. With infinite precision one could also always insert the
+ # extra vertex (it will get masked out by the label below anyways), but floating
+ # point inaccuracies (the point can have undergone a data->screen->data
+ # transform loop) can slightly shift the point and e.g. shift the angle computed
+ # below from exactly zero to nonzero.
+ pos = self.get_transform().inverted().transform(screen_pos)
+ if not np.allclose(pos, xys[idx]):
+ xys = np.insert(xys, idx, pos, axis=0)
+ codes = np.insert(codes, idx, Path.LINETO)
+
+ # Find the connected component where the label will be inserted. Note that a
+ # path always starts with a MOVETO, and we consider there's an implicit
+ # MOVETO (closing the last path) at the end.
+ movetos = (codes == Path.MOVETO).nonzero()[0]
+ start = movetos[movetos <= idx][-1]
+ try:
+ stop = movetos[movetos > idx][0]
+ except IndexError:
+ stop = len(codes)
+
+ # Restrict ourselves to the connected component.
+ cc_xys = xys[start:stop]
+ idx -= start
+
+ # If the path is closed, rotate it s.t. it starts at the label.
+ is_closed_path = codes[stop - 1] == Path.CLOSEPOLY
+ if is_closed_path:
+ cc_xys = np.concatenate([cc_xys[idx:-1], cc_xys[:idx+1]])
+ idx = 0
+
+ # Like np.interp, but additionally vectorized over fp.
+ def interp_vec(x, xp, fp): return [np.interp(x, xp, col) for col in fp.T]
+
+ # Use cumulative path lengths ("cpl") as curvilinear coordinate along contour.
+ screen_xys = self.get_transform().transform(cc_xys)
+ path_cpls = np.insert(
+ np.cumsum(np.hypot(*np.diff(screen_xys, axis=0).T)), 0, 0)
+ path_cpls -= path_cpls[idx]
+
+ # Use linear interpolation to get end coordinates of label.
+ target_cpls = np.array([-lw/2, lw/2])
+ if is_closed_path: # For closed paths, target from the other end.
+ target_cpls[0] += (path_cpls[-1] - path_cpls[0])
+ (sx0, sx1), (sy0, sy1) = interp_vec(target_cpls, path_cpls, screen_xys)
+ angle = np.rad2deg(np.arctan2(sy1 - sy0, sx1 - sx0)) # Screen space.
+ if self.rightside_up: # Fix angle so text is never upside-down
+ angle = (angle + 90) % 180 - 90
+
+ target_cpls += [-spacing, +spacing] # Expand range by spacing.
+
+ # Get indices near points of interest; use -1 as out of bounds marker.
+ i0, i1 = np.interp(target_cpls, path_cpls, range(len(path_cpls)),
+ left=-1, right=-1)
+ i0 = math.floor(i0)
+ i1 = math.ceil(i1)
+ (x0, x1), (y0, y1) = interp_vec(target_cpls, path_cpls, cc_xys)
+
+ # Actually break contours (dropping zero-len parts).
+ new_xy_blocks = []
+ new_code_blocks = []
+ if is_closed_path:
+ if i0 != -1 and i1 != -1:
+ # This is probably wrong in the case that the entire contour would
+ # be discarded, but ensures that a valid path is returned and is
+ # consistent with behavior of mpl <3.8
+ points = cc_xys[i1:i0+1]
+ new_xy_blocks.extend([[(x1, y1)], points, [(x0, y0)]])
+ nlines = len(points) + 1
+ new_code_blocks.extend([[Path.MOVETO], [Path.LINETO] * nlines])
+ else:
+ if i0 != -1:
+ new_xy_blocks.extend([cc_xys[:i0 + 1], [(x0, y0)]])
+ new_code_blocks.extend([[Path.MOVETO], [Path.LINETO] * (i0 + 1)])
+ if i1 != -1:
+ new_xy_blocks.extend([[(x1, y1)], cc_xys[i1:]])
+ new_code_blocks.extend([
+ [Path.MOVETO], [Path.LINETO] * (len(cc_xys) - i1)])
+
+ # Back to the full path.
+ xys = np.concatenate([xys[:start], *new_xy_blocks, xys[stop:]])
+ codes = np.concatenate([codes[:start], *new_code_blocks, codes[stop:]])
+
+ return angle, Path(xys, codes)
+
+ def add_label(self, x, y, rotation, lev, cvalue):
+ """Add a contour label, respecting whether *use_clabeltext* was set."""
+ data_x, data_y = self.axes.transData.inverted().transform((x, y))
+ t = Text(
+ data_x, data_y,
+ text=self.get_text(lev, self.labelFmt),
+ rotation=rotation,
+ horizontalalignment='center', verticalalignment='center',
+ zorder=self._clabel_zorder,
+ color=self.labelMappable.to_rgba(cvalue, alpha=self.get_alpha()),
+ fontproperties=self._label_font_props,
+ clip_box=self.axes.bbox)
+ if self._use_clabeltext:
+ data_rotation, = self.axes.transData.inverted().transform_angles(
+ [rotation], [[x, y]])
+ t.set(rotation=data_rotation, transform_rotates_text=True)
+ self.labelTexts.append(t)
+ self.labelCValues.append(cvalue)
+ self.labelXYs.append((x, y))
+ # Add label to plot here - useful for manual mode label selection
+ self.axes.add_artist(t)
+
+ def add_label_near(self, x, y, inline=True, inline_spacing=5,
+ transform=None):
+ """
+ Add a label near the point ``(x, y)``.
+
+ Parameters
+ ----------
+ x, y : float
+ The approximate location of the label.
+ inline : bool, default: True
+ If *True* remove the segment of the contour beneath the label.
+ inline_spacing : int, default: 5
+ Space in pixels to leave on each side of label when placing
+ inline. This spacing will be exact for labels at locations where
+ the contour is straight, less so for labels on curved contours.
+ transform : `.Transform` or `False`, default: ``self.axes.transData``
+ A transform applied to ``(x, y)`` before labeling. The default
+ causes ``(x, y)`` to be interpreted as data coordinates. `False`
+ is a synonym for `.IdentityTransform`; i.e. ``(x, y)`` should be
+ interpreted as display coordinates.
+ """
+
+ if transform is None:
+ transform = self.axes.transData
+ if transform:
+ x, y = transform.transform((x, y))
+
+ idx_level_min, idx_vtx_min, proj = self._find_nearest_contour(
+ (x, y), self.labelIndiceList)
+ path = self._paths[idx_level_min]
+ level = self.labelIndiceList.index(idx_level_min)
+ label_width = self._get_nth_label_width(level)
+ rotation, path = self._split_path_and_get_label_rotation(
+ path, idx_vtx_min, proj, label_width, inline_spacing)
+ self.add_label(*proj, rotation, self.labelLevelList[idx_level_min],
+ self.labelCValueList[idx_level_min])
+
+ if inline:
+ self._paths[idx_level_min] = path
+
+ def pop_label(self, index=-1):
+ """Defaults to removing last label, but any index can be supplied"""
+ self.labelCValues.pop(index)
+ t = self.labelTexts.pop(index)
+ t.remove()
+
+ def labels(self, inline, inline_spacing):
+ for idx, (icon, lev, cvalue) in enumerate(zip(
+ self.labelIndiceList,
+ self.labelLevelList,
+ self.labelCValueList,
+ )):
+ trans = self.get_transform()
+ label_width = self._get_nth_label_width(idx)
+ additions = []
+ for subpath in self._paths[icon]._iter_connected_components():
+ screen_xys = trans.transform(subpath.vertices)
+ # Check if long enough for a label
+ if self.print_label(screen_xys, label_width):
+ x, y, idx = self.locate_label(screen_xys, label_width)
+ rotation, path = self._split_path_and_get_label_rotation(
+ subpath, idx, (x, y),
+ label_width, inline_spacing)
+ self.add_label(x, y, rotation, lev, cvalue) # Really add label.
+ if inline: # If inline, add new contours
+ additions.append(path)
+ else: # If not adding label, keep old path
+ additions.append(subpath)
+ # After looping over all segments on a contour, replace old path by new one
+ # if inlining.
+ if inline:
+ self._paths[icon] = Path.make_compound_path(*additions)
+
+ def remove(self):
+ super().remove()
+ for text in self.labelTexts:
+ text.remove()
+
+
+def _find_closest_point_on_path(xys, p):
+ """
+ Parameters
+ ----------
+ xys : (N, 2) array-like
+ Coordinates of vertices.
+ p : (float, float)
+ Coordinates of point.
+
+ Returns
+ -------
+ d2min : float
+ Minimum square distance of *p* to *xys*.
+ proj : (float, float)
+ Projection of *p* onto *xys*.
+ imin : (int, int)
+ Consecutive indices of vertices of segment in *xys* where *proj* is.
+ Segments are considered as including their end-points; i.e. if the
+ closest point on the path is a node in *xys* with index *i*, this
+ returns ``(i-1, i)``. For the special case where *xys* is a single
+ point, this returns ``(0, 0)``.
+ """
+ if len(xys) == 1:
+ return (((p - xys[0]) ** 2).sum(), xys[0], (0, 0))
+ dxys = xys[1:] - xys[:-1] # Individual segment vectors.
+ norms = (dxys ** 2).sum(axis=1)
+ norms[norms == 0] = 1 # For zero-length segment, replace 0/0 by 0/1.
+ rel_projs = np.clip( # Project onto each segment in relative 0-1 coords.
+ ((p - xys[:-1]) * dxys).sum(axis=1) / norms,
+ 0, 1)[:, None]
+ projs = xys[:-1] + rel_projs * dxys # Projs. onto each segment, in (x, y).
+ d2s = ((projs - p) ** 2).sum(axis=1) # Squared distances.
+ imin = np.argmin(d2s)
+ return (d2s[imin], projs[imin], (imin, imin+1))
+
+
+_docstring.interpd.register(contour_set_attributes=r"""
+Attributes
+----------
+levels : array
+ The values of the contour levels.
+
+layers : array
+ Same as levels for line contours; half-way between
+ levels for filled contours. See ``ContourSet._process_colors``.
+""")
+
+
+@_docstring.interpd
+class ContourSet(ContourLabeler, mcoll.Collection):
+ """
+ Store a set of contour lines or filled regions.
+
+ User-callable method: `~.Axes.clabel`
+
+ Parameters
+ ----------
+ ax : `~matplotlib.axes.Axes`
+
+ levels : [level0, level1, ..., leveln]
+ A list of floating point numbers indicating the contour levels.
+
+ allsegs : [level0segs, level1segs, ...]
+ List of all the polygon segments for all the *levels*.
+ For contour lines ``len(allsegs) == len(levels)``, and for
+ filled contour regions ``len(allsegs) = len(levels)-1``. The lists
+ should look like ::
+
+ level0segs = [polygon0, polygon1, ...]
+ polygon0 = [[x0, y0], [x1, y1], ...]
+
+ allkinds : ``None`` or [level0kinds, level1kinds, ...]
+ Optional list of all the polygon vertex kinds (code types), as
+ described and used in Path. This is used to allow multiply-
+ connected paths such as holes within filled polygons.
+ If not ``None``, ``len(allkinds) == len(allsegs)``. The lists
+ should look like ::
+
+ level0kinds = [polygon0kinds, ...]
+ polygon0kinds = [vertexcode0, vertexcode1, ...]
+
+ If *allkinds* is not ``None``, usually all polygons for a
+ particular contour level are grouped together so that
+ ``level0segs = [polygon0]`` and ``level0kinds = [polygon0kinds]``.
+
+ **kwargs
+ Keyword arguments are as described in the docstring of
+ `~.Axes.contour`.
+
+ %(contour_set_attributes)s
+ """
+
+ def __init__(self, ax, *args,
+ levels=None, filled=False, linewidths=None, linestyles=None,
+ hatches=(None,), alpha=None, origin=None, extent=None,
+ cmap=None, colors=None, norm=None, vmin=None, vmax=None,
+ colorizer=None, extend='neither', antialiased=None, nchunk=0,
+ locator=None, transform=None, negative_linestyles=None, clip_path=None,
+ **kwargs):
+ """
+ Draw contour lines or filled regions, depending on
+ whether keyword arg *filled* is ``False`` (default) or ``True``.
+
+ Call signature::
+
+ ContourSet(ax, levels, allsegs, [allkinds], **kwargs)
+
+ Parameters
+ ----------
+ ax : `~matplotlib.axes.Axes`
+ The `~.axes.Axes` object to draw on.
+
+ levels : [level0, level1, ..., leveln]
+ A list of floating point numbers indicating the contour
+ levels.
+
+ allsegs : [level0segs, level1segs, ...]
+ List of all the polygon segments for all the *levels*.
+ For contour lines ``len(allsegs) == len(levels)``, and for
+ filled contour regions ``len(allsegs) = len(levels)-1``. The lists
+ should look like ::
+
+ level0segs = [polygon0, polygon1, ...]
+ polygon0 = [[x0, y0], [x1, y1], ...]
+
+ allkinds : [level0kinds, level1kinds, ...], optional
+ Optional list of all the polygon vertex kinds (code types), as
+ described and used in Path. This is used to allow multiply-
+ connected paths such as holes within filled polygons.
+ If not ``None``, ``len(allkinds) == len(allsegs)``. The lists
+ should look like ::
+
+ level0kinds = [polygon0kinds, ...]
+ polygon0kinds = [vertexcode0, vertexcode1, ...]
+
+ If *allkinds* is not ``None``, usually all polygons for a
+ particular contour level are grouped together so that
+ ``level0segs = [polygon0]`` and ``level0kinds = [polygon0kinds]``.
+
+ **kwargs
+ Keyword arguments are as described in the docstring of
+ `~.Axes.contour`.
+ """
+ if antialiased is None and filled:
+ # Eliminate artifacts; we are not stroking the boundaries.
+ antialiased = False
+ # The default for line contours will be taken from the
+ # LineCollection default, which uses :rc:`lines.antialiased`.
+ super().__init__(
+ antialiaseds=antialiased,
+ alpha=alpha,
+ clip_path=clip_path,
+ transform=transform,
+ colorizer=colorizer,
+ )
+ self.axes = ax
+ self.levels = levels
+ self.filled = filled
+ self.hatches = hatches
+ self.origin = origin
+ self.extent = extent
+ self.colors = colors
+ self.extend = extend
+
+ self.nchunk = nchunk
+ self.locator = locator
+
+ if colorizer:
+ self._set_colorizer_check_keywords(colorizer, cmap=cmap,
+ norm=norm, vmin=vmin,
+ vmax=vmax, colors=colors)
+ norm = colorizer.norm
+ cmap = colorizer.cmap
+ if (isinstance(norm, mcolors.LogNorm)
+ or isinstance(self.locator, ticker.LogLocator)):
+ self.logscale = True
+ if norm is None:
+ norm = mcolors.LogNorm()
+ else:
+ self.logscale = False
+
+ _api.check_in_list([None, 'lower', 'upper', 'image'], origin=origin)
+ if self.extent is not None and len(self.extent) != 4:
+ raise ValueError(
+ "If given, 'extent' must be None or (x0, x1, y0, y1)")
+ if self.colors is not None and cmap is not None:
+ raise ValueError('Either colors or cmap must be None')
+ if self.origin == 'image':
+ self.origin = mpl.rcParams['image.origin']
+
+ self._orig_linestyles = linestyles # Only kept for user access.
+ self.negative_linestyles = negative_linestyles
+ # If negative_linestyles was not defined as a keyword argument, define
+ # negative_linestyles with rcParams
+ if self.negative_linestyles is None:
+ self.negative_linestyles = \
+ mpl.rcParams['contour.negative_linestyle']
+
+ kwargs = self._process_args(*args, **kwargs)
+ self._process_levels()
+
+ self._extend_min = self.extend in ['min', 'both']
+ self._extend_max = self.extend in ['max', 'both']
+ if self.colors is not None:
+ if mcolors.is_color_like(self.colors):
+ color_sequence = [self.colors]
+ else:
+ color_sequence = self.colors
+
+ ncolors = len(self.levels)
+ if self.filled:
+ ncolors -= 1
+ i0 = 0
+
+ # Handle the case where colors are given for the extended
+ # parts of the contour.
+
+ use_set_under_over = False
+ # if we are extending the lower end, and we've been given enough
+ # colors then skip the first color in the resulting cmap. For the
+ # extend_max case we don't need to worry about passing more colors
+ # than ncolors as ListedColormap will clip.
+ total_levels = (ncolors +
+ int(self._extend_min) +
+ int(self._extend_max))
+ if (len(color_sequence) == total_levels and
+ (self._extend_min or self._extend_max)):
+ use_set_under_over = True
+ if self._extend_min:
+ i0 = 1
+
+ cmap = mcolors.ListedColormap(color_sequence[i0:None], N=ncolors)
+
+ if use_set_under_over:
+ if self._extend_min:
+ cmap.set_under(color_sequence[0])
+ if self._extend_max:
+ cmap.set_over(color_sequence[-1])
+
+ # label lists must be initialized here
+ self.labelTexts = []
+ self.labelCValues = []
+
+ self.set_cmap(cmap)
+ if norm is not None:
+ self.set_norm(norm)
+ with self.norm.callbacks.blocked(signal="changed"):
+ if vmin is not None:
+ self.norm.vmin = vmin
+ if vmax is not None:
+ self.norm.vmax = vmax
+ self.norm._changed()
+ self._process_colors()
+
+ if self._paths is None:
+ self._paths = self._make_paths_from_contour_generator()
+
+ if self.filled:
+ if linewidths is not None:
+ _api.warn_external('linewidths is ignored by contourf')
+ # Lower and upper contour levels.
+ lowers, uppers = self._get_lowers_and_uppers()
+ self.set(
+ edgecolor="none",
+ # Default zorder taken from Collection
+ zorder=kwargs.pop("zorder", 1),
+ )
+
+ else:
+ self.set(
+ facecolor="none",
+ linewidths=self._process_linewidths(linewidths),
+ linestyle=self._process_linestyles(linestyles),
+ # Default zorder taken from LineCollection, which is higher
+ # than for filled contours so that lines are displayed on top.
+ zorder=kwargs.pop("zorder", 2),
+ label="_nolegend_",
+ )
+
+ self.axes.add_collection(self, autolim=False)
+ self.sticky_edges.x[:] = [self._mins[0], self._maxs[0]]
+ self.sticky_edges.y[:] = [self._mins[1], self._maxs[1]]
+ self.axes.update_datalim([self._mins, self._maxs])
+ self.axes.autoscale_view(tight=True)
+
+ self.changed() # set the colors
+
+ if kwargs:
+ _api.warn_external(
+ 'The following kwargs were not used by contour: ' +
+ ", ".join(map(repr, kwargs))
+ )
+
+ allsegs = property(lambda self: [
+ [subp.vertices for subp in p._iter_connected_components()]
+ for p in self.get_paths()])
+ allkinds = property(lambda self: [
+ [subp.codes for subp in p._iter_connected_components()]
+ for p in self.get_paths()])
+ alpha = property(lambda self: self.get_alpha())
+ linestyles = property(lambda self: self._orig_linestyles)
+
+ def get_transform(self):
+ """Return the `.Transform` instance used by this ContourSet."""
+ if self._transform is None:
+ self._transform = self.axes.transData
+ elif (not isinstance(self._transform, mtransforms.Transform)
+ and hasattr(self._transform, '_as_mpl_transform')):
+ self._transform = self._transform._as_mpl_transform(self.axes)
+ return self._transform
+
+ def __getstate__(self):
+ state = self.__dict__.copy()
+ # the C object _contour_generator cannot currently be pickled. This
+ # isn't a big issue as it is not actually used once the contour has
+ # been calculated.
+ state['_contour_generator'] = None
+ return state
+
+ def legend_elements(self, variable_name='x', str_format=str):
+ """
+ Return a list of artists and labels suitable for passing through
+ to `~.Axes.legend` which represent this ContourSet.
+
+ The labels have the form "0 < x <= 1" stating the data ranges which
+ the artists represent.
+
+ Parameters
+ ----------
+ variable_name : str
+ The string used inside the inequality used on the labels.
+ str_format : function: float -> str
+ Function used to format the numbers in the labels.
+
+ Returns
+ -------
+ artists : list[`.Artist`]
+ A list of the artists.
+ labels : list[str]
+ A list of the labels.
+ """
+ artists = []
+ labels = []
+
+ if self.filled:
+ lowers, uppers = self._get_lowers_and_uppers()
+ n_levels = len(self._paths)
+ for idx in range(n_levels):
+ artists.append(mpatches.Rectangle(
+ (0, 0), 1, 1,
+ facecolor=self.get_facecolor()[idx],
+ hatch=self.hatches[idx % len(self.hatches)],
+ ))
+ lower = str_format(lowers[idx])
+ upper = str_format(uppers[idx])
+ if idx == 0 and self.extend in ('min', 'both'):
+ labels.append(fr'${variable_name} \leq {lower}s$')
+ elif idx == n_levels - 1 and self.extend in ('max', 'both'):
+ labels.append(fr'${variable_name} > {upper}s$')
+ else:
+ labels.append(fr'${lower} < {variable_name} \leq {upper}$')
+ else:
+ for idx, level in enumerate(self.levels):
+ artists.append(Line2D(
+ [], [],
+ color=self.get_edgecolor()[idx],
+ linewidth=self.get_linewidths()[idx],
+ linestyle=self.get_linestyles()[idx],
+ ))
+ labels.append(fr'${variable_name} = {str_format(level)}$')
+
+ return artists, labels
+
+ def _process_args(self, *args, **kwargs):
+ """
+ Process *args* and *kwargs*; override in derived classes.
+
+ Must set self.levels, self.zmin and self.zmax, and update Axes limits.
+ """
+ self.levels = args[0]
+ allsegs = args[1]
+ allkinds = args[2] if len(args) > 2 else None
+ self.zmax = np.max(self.levels)
+ self.zmin = np.min(self.levels)
+
+ if allkinds is None:
+ allkinds = [[None] * len(segs) for segs in allsegs]
+
+ # Check lengths of levels and allsegs.
+ if self.filled:
+ if len(allsegs) != len(self.levels) - 1:
+ raise ValueError('must be one less number of segments as '
+ 'levels')
+ else:
+ if len(allsegs) != len(self.levels):
+ raise ValueError('must be same number of segments as levels')
+
+ # Check length of allkinds.
+ if len(allkinds) != len(allsegs):
+ raise ValueError('allkinds has different length to allsegs')
+
+ # Determine x, y bounds and update axes data limits.
+ flatseglist = [s for seg in allsegs for s in seg]
+ points = np.concatenate(flatseglist, axis=0)
+ self._mins = points.min(axis=0)
+ self._maxs = points.max(axis=0)
+
+ # Each entry in (allsegs, allkinds) is a list of (segs, kinds): segs is a list
+ # of (N, 2) arrays of xy coordinates, kinds is a list of arrays of corresponding
+ # pathcodes. However, kinds can also be None; in which case all paths in that
+ # list are codeless (this case is normalized above). These lists are used to
+ # construct paths, which then get concatenated.
+ self._paths = [Path.make_compound_path(*map(Path, segs, kinds))
+ for segs, kinds in zip(allsegs, allkinds)]
+
+ return kwargs
+
+ def _make_paths_from_contour_generator(self):
+ """Compute ``paths`` using C extension."""
+ if self._paths is not None:
+ return self._paths
+ cg = self._contour_generator
+ empty_path = Path(np.empty((0, 2)))
+ vertices_and_codes = (
+ map(cg.create_filled_contour, *self._get_lowers_and_uppers())
+ if self.filled else
+ map(cg.create_contour, self.levels))
+ return [Path(np.concatenate(vs), np.concatenate(cs)) if len(vs) else empty_path
+ for vs, cs in vertices_and_codes]
+
+ def _get_lowers_and_uppers(self):
+ """
+ Return ``(lowers, uppers)`` for filled contours.
+ """
+ lowers = self._levels[:-1]
+ if self.zmin == lowers[0]:
+ # Include minimum values in lowest interval
+ lowers = lowers.copy() # so we don't change self._levels
+ if self.logscale:
+ lowers[0] = 0.99 * self.zmin
+ else:
+ lowers[0] -= 1
+ uppers = self._levels[1:]
+ return (lowers, uppers)
+
+ def changed(self):
+ if not hasattr(self, "cvalues"):
+ self._process_colors() # Sets cvalues.
+ # Force an autoscale immediately because self.to_rgba() calls
+ # autoscale_None() internally with the data passed to it,
+ # so if vmin/vmax are not set yet, this would override them with
+ # content from *cvalues* rather than levels like we want
+ self.norm.autoscale_None(self.levels)
+ self.set_array(self.cvalues)
+ self.update_scalarmappable()
+ alphas = np.broadcast_to(self.get_alpha(), len(self.cvalues))
+ for label, cv, alpha in zip(self.labelTexts, self.labelCValues, alphas):
+ label.set_alpha(alpha)
+ label.set_color(self.labelMappable.to_rgba(cv))
+ super().changed()
+
+ def _autolev(self, N):
+ """
+ Select contour levels to span the data.
+
+ The target number of levels, *N*, is used only when the
+ scale is not log and default locator is used.
+
+ We need two more levels for filled contours than for
+ line contours, because for the latter we need to specify
+ the lower and upper boundary of each range. For example,
+ a single contour boundary, say at z = 0, requires only
+ one contour line, but two filled regions, and therefore
+ three levels to provide boundaries for both regions.
+ """
+ if self.locator is None:
+ if self.logscale:
+ self.locator = ticker.LogLocator()
+ else:
+ self.locator = ticker.MaxNLocator(N + 1, min_n_ticks=1)
+
+ lev = self.locator.tick_values(self.zmin, self.zmax)
+
+ try:
+ if self.locator._symmetric:
+ return lev
+ except AttributeError:
+ pass
+
+ # Trim excess levels the locator may have supplied.
+ under = np.nonzero(lev < self.zmin)[0]
+ i0 = under[-1] if len(under) else 0
+ over = np.nonzero(lev > self.zmax)[0]
+ i1 = over[0] + 1 if len(over) else len(lev)
+ if self.extend in ('min', 'both'):
+ i0 += 1
+ if self.extend in ('max', 'both'):
+ i1 -= 1
+
+ if i1 - i0 < 3:
+ i0, i1 = 0, len(lev)
+
+ return lev[i0:i1]
+
+ def _process_contour_level_args(self, args, z_dtype):
+ """
+ Determine the contour levels and store in self.levels.
+ """
+ if self.levels is None:
+ if args:
+ levels_arg = args[0]
+ elif np.issubdtype(z_dtype, bool):
+ if self.filled:
+ levels_arg = [0, .5, 1]
+ else:
+ levels_arg = [.5]
+ else:
+ levels_arg = 7 # Default, hard-wired.
+ else:
+ levels_arg = self.levels
+ if isinstance(levels_arg, Integral):
+ self.levels = self._autolev(levels_arg)
+ else:
+ self.levels = np.asarray(levels_arg, np.float64)
+ if self.filled and len(self.levels) < 2:
+ raise ValueError("Filled contours require at least 2 levels.")
+ if len(self.levels) > 1 and np.min(np.diff(self.levels)) <= 0.0:
+ raise ValueError("Contour levels must be increasing")
+
+ def _process_levels(self):
+ """
+ Assign values to :attr:`layers` based on :attr:`levels`,
+ adding extended layers as needed if contours are filled.
+
+ For line contours, layers simply coincide with levels;
+ a line is a thin layer. No extended levels are needed
+ with line contours.
+ """
+ # Make a private _levels to include extended regions; we
+ # want to leave the original levels attribute unchanged.
+ # (Colorbar needs this even for line contours.)
+ self._levels = list(self.levels)
+
+ if self.logscale:
+ lower, upper = 1e-250, 1e250
+ else:
+ lower, upper = -1e250, 1e250
+
+ if self.extend in ('both', 'min'):
+ self._levels.insert(0, lower)
+ if self.extend in ('both', 'max'):
+ self._levels.append(upper)
+ self._levels = np.asarray(self._levels)
+
+ if not self.filled:
+ self.layers = self.levels
+ return
+
+ # Layer values are mid-way between levels in screen space.
+ if self.logscale:
+ # Avoid overflow by taking sqrt before multiplying.
+ self.layers = (np.sqrt(self._levels[:-1])
+ * np.sqrt(self._levels[1:]))
+ else:
+ self.layers = 0.5 * (self._levels[:-1] + self._levels[1:])
+
+ def _process_colors(self):
+ """
+ Color argument processing for contouring.
+
+ Note that we base the colormapping on the contour levels
+ and layers, not on the actual range of the Z values. This
+ means we don't have to worry about bad values in Z, and we
+ always have the full dynamic range available for the selected
+ levels.
+
+ The color is based on the midpoint of the layer, except for
+ extended end layers. By default, the norm vmin and vmax
+ are the extreme values of the non-extended levels. Hence,
+ the layer color extremes are not the extreme values of
+ the colormap itself, but approach those values as the number
+ of levels increases. An advantage of this scheme is that
+ line contours, when added to filled contours, take on
+ colors that are consistent with those of the filled regions;
+ for example, a contour line on the boundary between two
+ regions will have a color intermediate between those
+ of the regions.
+
+ """
+ self.monochrome = self.cmap.monochrome
+ if self.colors is not None:
+ # Generate integers for direct indexing.
+ i0, i1 = 0, len(self.levels)
+ if self.filled:
+ i1 -= 1
+ # Out of range indices for over and under:
+ if self.extend in ('both', 'min'):
+ i0 -= 1
+ if self.extend in ('both', 'max'):
+ i1 += 1
+ self.cvalues = list(range(i0, i1))
+ self.set_norm(mcolors.NoNorm())
+ else:
+ self.cvalues = self.layers
+ self.norm.autoscale_None(self.levels)
+ self.set_array(self.cvalues)
+ self.update_scalarmappable()
+ if self.extend in ('both', 'max', 'min'):
+ self.norm.clip = False
+
+ def _process_linewidths(self, linewidths):
+ Nlev = len(self.levels)
+ if linewidths is None:
+ default_linewidth = mpl.rcParams['contour.linewidth']
+ if default_linewidth is None:
+ default_linewidth = mpl.rcParams['lines.linewidth']
+ return [default_linewidth] * Nlev
+ elif not np.iterable(linewidths):
+ return [linewidths] * Nlev
+ else:
+ linewidths = list(linewidths)
+ return (linewidths * math.ceil(Nlev / len(linewidths)))[:Nlev]
+
+ def _process_linestyles(self, linestyles):
+ Nlev = len(self.levels)
+ if linestyles is None:
+ tlinestyles = ['solid'] * Nlev
+ if self.monochrome:
+ eps = - (self.zmax - self.zmin) * 1e-15
+ for i, lev in enumerate(self.levels):
+ if lev < eps:
+ tlinestyles[i] = self.negative_linestyles
+ else:
+ if isinstance(linestyles, str):
+ tlinestyles = [linestyles] * Nlev
+ elif np.iterable(linestyles):
+ tlinestyles = list(linestyles)
+ if len(tlinestyles) < Nlev:
+ nreps = int(np.ceil(Nlev / len(linestyles)))
+ tlinestyles = tlinestyles * nreps
+ if len(tlinestyles) > Nlev:
+ tlinestyles = tlinestyles[:Nlev]
+ else:
+ raise ValueError("Unrecognized type for linestyles kwarg")
+ return tlinestyles
+
+ def _find_nearest_contour(self, xy, indices=None):
+ """
+ Find the point in the unfilled contour plot that is closest (in screen
+ space) to point *xy*.
+
+ Parameters
+ ----------
+ xy : tuple[float, float]
+ The reference point (in screen space).
+ indices : list of int or None, default: None
+ Indices of contour levels to consider. If None (the default), all levels
+ are considered.
+
+ Returns
+ -------
+ idx_level_min : int
+ The index of the contour level closest to *xy*.
+ idx_vtx_min : int
+ The index of the `.Path` segment closest to *xy* (at that level).
+ proj : (float, float)
+ The point in the contour plot closest to *xy*.
+ """
+
+ # Convert each contour segment to pixel coordinates and then compare the given
+ # point to those coordinates for each contour. This is fast enough in normal
+ # cases, but speedups may be possible.
+
+ if self.filled:
+ raise ValueError("Method does not support filled contours")
+
+ if indices is None:
+ indices = range(len(self._paths))
+
+ d2min = np.inf
+ idx_level_min = idx_vtx_min = proj_min = None
+
+ for idx_level in indices:
+ path = self._paths[idx_level]
+ idx_vtx_start = 0
+ for subpath in path._iter_connected_components():
+ if not len(subpath.vertices):
+ continue
+ lc = self.get_transform().transform(subpath.vertices)
+ d2, proj, leg = _find_closest_point_on_path(lc, xy)
+ if d2 < d2min:
+ d2min = d2
+ idx_level_min = idx_level
+ idx_vtx_min = leg[1] + idx_vtx_start
+ proj_min = proj
+ idx_vtx_start += len(subpath)
+
+ return idx_level_min, idx_vtx_min, proj_min
+
+ def find_nearest_contour(self, x, y, indices=None, pixel=True):
+ """
+ Find the point in the contour plot that is closest to ``(x, y)``.
+
+ This method does not support filled contours.
+
+ Parameters
+ ----------
+ x, y : float
+ The reference point.
+ indices : list of int or None, default: None
+ Indices of contour levels to consider. If None (the default), all
+ levels are considered.
+ pixel : bool, default: True
+ If *True*, measure distance in pixel (screen) space, which is
+ useful for manual contour labeling; else, measure distance in axes
+ space.
+
+ Returns
+ -------
+ path : int
+ The index of the path that is closest to ``(x, y)``. Each path corresponds
+ to one contour level.
+ subpath : int
+ The index within that closest path of the subpath that is closest to
+ ``(x, y)``. Each subpath corresponds to one unbroken contour line.
+ index : int
+ The index of the vertices within that subpath that are closest to
+ ``(x, y)``.
+ xmin, ymin : float
+ The point in the contour plot that is closest to ``(x, y)``.
+ d2 : float
+ The squared distance from ``(xmin, ymin)`` to ``(x, y)``.
+ """
+ segment = index = d2 = None
+
+ with ExitStack() as stack:
+ if not pixel:
+ # _find_nearest_contour works in pixel space. We want axes space, so
+ # effectively disable the transformation here by setting to identity.
+ stack.enter_context(self._cm_set(
+ transform=mtransforms.IdentityTransform()))
+
+ i_level, i_vtx, (xmin, ymin) = self._find_nearest_contour((x, y), indices)
+
+ if i_level is not None:
+ cc_cumlens = np.cumsum(
+ [*map(len, self._paths[i_level]._iter_connected_components())])
+ segment = cc_cumlens.searchsorted(i_vtx, "right")
+ index = i_vtx if segment == 0 else i_vtx - cc_cumlens[segment - 1]
+ d2 = (xmin-x)**2 + (ymin-y)**2
+
+ return (i_level, segment, index, xmin, ymin, d2)
+
+ def draw(self, renderer):
+ paths = self._paths
+ n_paths = len(paths)
+ if not self.filled or all(hatch is None for hatch in self.hatches):
+ super().draw(renderer)
+ return
+ # In presence of hatching, draw contours one at a time.
+ edgecolors = self.get_edgecolors()
+ if edgecolors.size == 0:
+ edgecolors = ("none",)
+ for idx in range(n_paths):
+ with cbook._setattr_cm(self, _paths=[paths[idx]]), self._cm_set(
+ hatch=self.hatches[idx % len(self.hatches)],
+ array=[self.get_array()[idx]],
+ linewidths=[self.get_linewidths()[idx % len(self.get_linewidths())]],
+ linestyles=[self.get_linestyles()[idx % len(self.get_linestyles())]],
+ edgecolors=edgecolors[idx % len(edgecolors)],
+ ):
+ super().draw(renderer)
+
+
+@_docstring.interpd
+class QuadContourSet(ContourSet):
+ """
+ Create and store a set of contour lines or filled regions.
+
+ This class is typically not instantiated directly by the user but by
+ `~.Axes.contour` and `~.Axes.contourf`.
+
+ %(contour_set_attributes)s
+ """
+
+ def _process_args(self, *args, corner_mask=None, algorithm=None, **kwargs):
+ """
+ Process args and kwargs.
+ """
+ if args and isinstance(args[0], QuadContourSet):
+ if self.levels is None:
+ self.levels = args[0].levels
+ self.zmin = args[0].zmin
+ self.zmax = args[0].zmax
+ self._corner_mask = args[0]._corner_mask
+ contour_generator = args[0]._contour_generator
+ self._mins = args[0]._mins
+ self._maxs = args[0]._maxs
+ self._algorithm = args[0]._algorithm
+ else:
+ import contourpy
+
+ if algorithm is None:
+ algorithm = mpl.rcParams['contour.algorithm']
+ mpl.rcParams.validate["contour.algorithm"](algorithm)
+ self._algorithm = algorithm
+
+ if corner_mask is None:
+ if self._algorithm == "mpl2005":
+ # mpl2005 does not support corner_mask=True so if not
+ # specifically requested then disable it.
+ corner_mask = False
+ else:
+ corner_mask = mpl.rcParams['contour.corner_mask']
+ self._corner_mask = corner_mask
+
+ x, y, z = self._contour_args(args, kwargs)
+
+ contour_generator = contourpy.contour_generator(
+ x, y, z, name=self._algorithm, corner_mask=self._corner_mask,
+ line_type=contourpy.LineType.SeparateCode,
+ fill_type=contourpy.FillType.OuterCode,
+ chunk_size=self.nchunk)
+
+ t = self.get_transform()
+
+ # if the transform is not trans data, and some part of it
+ # contains transData, transform the xs and ys to data coordinates
+ if (t != self.axes.transData and
+ any(t.contains_branch_seperately(self.axes.transData))):
+ trans_to_data = t - self.axes.transData
+ pts = np.vstack([x.flat, y.flat]).T
+ transformed_pts = trans_to_data.transform(pts)
+ x = transformed_pts[..., 0]
+ y = transformed_pts[..., 1]
+
+ self._mins = [ma.min(x), ma.min(y)]
+ self._maxs = [ma.max(x), ma.max(y)]
+
+ self._contour_generator = contour_generator
+
+ return kwargs
+
+ def _contour_args(self, args, kwargs):
+ if self.filled:
+ fn = 'contourf'
+ else:
+ fn = 'contour'
+ nargs = len(args)
+
+ if 0 < nargs <= 2:
+ z, *args = args
+ z = ma.asarray(z)
+ x, y = self._initialize_x_y(z)
+ elif 2 < nargs <= 4:
+ x, y, z_orig, *args = args
+ x, y, z = self._check_xyz(x, y, z_orig, kwargs)
+
+ else:
+ raise _api.nargs_error(fn, takes="from 1 to 4", given=nargs)
+ z = ma.masked_invalid(z, copy=False)
+ self.zmax = z.max().astype(float)
+ self.zmin = z.min().astype(float)
+ if self.logscale and self.zmin <= 0:
+ z = ma.masked_where(z <= 0, z)
+ _api.warn_external('Log scale: values of z <= 0 have been masked')
+ self.zmin = z.min().astype(float)
+ self._process_contour_level_args(args, z.dtype)
+ return (x, y, z)
+
+ def _check_xyz(self, x, y, z, kwargs):
+ """
+ Check that the shapes of the input arrays match; if x and y are 1D,
+ convert them to 2D using meshgrid.
+ """
+ x, y = self.axes._process_unit_info([("x", x), ("y", y)], kwargs)
+
+ x = np.asarray(x, dtype=np.float64)
+ y = np.asarray(y, dtype=np.float64)
+ z = ma.asarray(z)
+
+ if z.ndim != 2:
+ raise TypeError(f"Input z must be 2D, not {z.ndim}D")
+ if z.shape[0] < 2 or z.shape[1] < 2:
+ raise TypeError(f"Input z must be at least a (2, 2) shaped array, "
+ f"but has shape {z.shape}")
+ Ny, Nx = z.shape
+
+ if x.ndim != y.ndim:
+ raise TypeError(f"Number of dimensions of x ({x.ndim}) and y "
+ f"({y.ndim}) do not match")
+ if x.ndim == 1:
+ nx, = x.shape
+ ny, = y.shape
+ if nx != Nx:
+ raise TypeError(f"Length of x ({nx}) must match number of "
+ f"columns in z ({Nx})")
+ if ny != Ny:
+ raise TypeError(f"Length of y ({ny}) must match number of "
+ f"rows in z ({Ny})")
+ x, y = np.meshgrid(x, y)
+ elif x.ndim == 2:
+ if x.shape != z.shape:
+ raise TypeError(
+ f"Shapes of x {x.shape} and z {z.shape} do not match")
+ if y.shape != z.shape:
+ raise TypeError(
+ f"Shapes of y {y.shape} and z {z.shape} do not match")
+ else:
+ raise TypeError(f"Inputs x and y must be 1D or 2D, not {x.ndim}D")
+
+ return x, y, z
+
+ def _initialize_x_y(self, z):
+ """
+ Return X, Y arrays such that contour(Z) will match imshow(Z)
+ if origin is not None.
+ The center of pixel Z[i, j] depends on origin:
+ if origin is None, x = j, y = i;
+ if origin is 'lower', x = j + 0.5, y = i + 0.5;
+ if origin is 'upper', x = j + 0.5, y = Nrows - i - 0.5
+ If extent is not None, x and y will be scaled to match,
+ as in imshow.
+ If origin is None and extent is not None, then extent
+ will give the minimum and maximum values of x and y.
+ """
+ if z.ndim != 2:
+ raise TypeError(f"Input z must be 2D, not {z.ndim}D")
+ elif z.shape[0] < 2 or z.shape[1] < 2:
+ raise TypeError(f"Input z must be at least a (2, 2) shaped array, "
+ f"but has shape {z.shape}")
+ else:
+ Ny, Nx = z.shape
+ if self.origin is None: # Not for image-matching.
+ if self.extent is None:
+ return np.meshgrid(np.arange(Nx), np.arange(Ny))
+ else:
+ x0, x1, y0, y1 = self.extent
+ x = np.linspace(x0, x1, Nx)
+ y = np.linspace(y0, y1, Ny)
+ return np.meshgrid(x, y)
+ # Match image behavior:
+ if self.extent is None:
+ x0, x1, y0, y1 = (0, Nx, 0, Ny)
+ else:
+ x0, x1, y0, y1 = self.extent
+ dx = (x1 - x0) / Nx
+ dy = (y1 - y0) / Ny
+ x = x0 + (np.arange(Nx) + 0.5) * dx
+ y = y0 + (np.arange(Ny) + 0.5) * dy
+ if self.origin == 'upper':
+ y = y[::-1]
+ return np.meshgrid(x, y)
+
+
+_docstring.interpd.register(contour_doc="""
+`.contour` and `.contourf` draw contour lines and filled contours,
+respectively. Except as noted, function signatures and return values
+are the same for both versions.
+
+Parameters
+----------
+X, Y : array-like, optional
+ The coordinates of the values in *Z*.
+
+ *X* and *Y* must both be 2D with the same shape as *Z* (e.g.
+ created via `numpy.meshgrid`), or they must both be 1-D such
+ that ``len(X) == N`` is the number of columns in *Z* and
+ ``len(Y) == M`` is the number of rows in *Z*.
+
+ *X* and *Y* must both be ordered monotonically.
+
+ If not given, they are assumed to be integer indices, i.e.
+ ``X = range(N)``, ``Y = range(M)``.
+
+Z : (M, N) array-like
+ The height values over which the contour is drawn. Color-mapping is
+ controlled by *cmap*, *norm*, *vmin*, and *vmax*.
+
+levels : int or array-like, optional
+ Determines the number and positions of the contour lines / regions.
+
+ If an int *n*, use `~matplotlib.ticker.MaxNLocator`, which tries
+ to automatically choose no more than *n+1* "nice" contour levels
+ between minimum and maximum numeric values of *Z*.
+
+ If array-like, draw contour lines at the specified levels.
+ The values must be in increasing order.
+
+Returns
+-------
+`~.contour.QuadContourSet`
+
+Other Parameters
+----------------
+corner_mask : bool, default: :rc:`contour.corner_mask`
+ Enable/disable corner masking, which only has an effect if *Z* is
+ a masked array. If ``False``, any quad touching a masked point is
+ masked out. If ``True``, only the triangular corners of quads
+ nearest those points are always masked out, other triangular
+ corners comprising three unmasked points are contoured as usual.
+
+colors : :mpltype:`color` or list of :mpltype:`color`, optional
+ The colors of the levels, i.e. the lines for `.contour` and the
+ areas for `.contourf`.
+
+ The sequence is cycled for the levels in ascending order. If the
+ sequence is shorter than the number of levels, it's repeated.
+
+ As a shortcut, a single color may be used in place of one-element lists, i.e.
+ ``'red'`` instead of ``['red']`` to color all levels with the same color.
+
+ .. versionchanged:: 3.10
+ Previously a single color had to be expressed as a string, but now any
+ valid color format may be passed.
+
+ By default (value *None*), the colormap specified by *cmap*
+ will be used.
+
+alpha : float, default: 1
+ The alpha blending value, between 0 (transparent) and 1 (opaque).
+
+%(cmap_doc)s
+
+ This parameter is ignored if *colors* is set.
+
+%(norm_doc)s
+
+ This parameter is ignored if *colors* is set.
+
+%(vmin_vmax_doc)s
+
+ If *vmin* or *vmax* are not given, the default color scaling is based on
+ *levels*.
+
+ This parameter is ignored if *colors* is set.
+
+%(colorizer_doc)s
+
+ This parameter is ignored if *colors* is set.
+
+origin : {*None*, 'upper', 'lower', 'image'}, default: None
+ Determines the orientation and exact position of *Z* by specifying
+ the position of ``Z[0, 0]``. This is only relevant, if *X*, *Y*
+ are not given.
+
+ - *None*: ``Z[0, 0]`` is at X=0, Y=0 in the lower left corner.
+ - 'lower': ``Z[0, 0]`` is at X=0.5, Y=0.5 in the lower left corner.
+ - 'upper': ``Z[0, 0]`` is at X=N+0.5, Y=0.5 in the upper left
+ corner.
+ - 'image': Use the value from :rc:`image.origin`.
+
+extent : (x0, x1, y0, y1), optional
+ If *origin* is not *None*, then *extent* is interpreted as in
+ `.imshow`: it gives the outer pixel boundaries. In this case, the
+ position of Z[0, 0] is the center of the pixel, not a corner. If
+ *origin* is *None*, then (*x0*, *y0*) is the position of Z[0, 0],
+ and (*x1*, *y1*) is the position of Z[-1, -1].
+
+ This argument is ignored if *X* and *Y* are specified in the call
+ to contour.
+
+locator : ticker.Locator subclass, optional
+ The locator is used to determine the contour levels if they
+ are not given explicitly via *levels*.
+ Defaults to `~.ticker.MaxNLocator`.
+
+extend : {'neither', 'both', 'min', 'max'}, default: 'neither'
+ Determines the ``contourf``-coloring of values that are outside the
+ *levels* range.
+
+ If 'neither', values outside the *levels* range are not colored.
+ If 'min', 'max' or 'both', color the values below, above or below
+ and above the *levels* range.
+
+ Values below ``min(levels)`` and above ``max(levels)`` are mapped
+ to the under/over values of the `.Colormap`. Note that most
+ colormaps do not have dedicated colors for these by default, so
+ that the over and under values are the edge values of the colormap.
+ You may want to set these values explicitly using
+ `.Colormap.set_under` and `.Colormap.set_over`.
+
+ .. note::
+
+ An existing `.QuadContourSet` does not get notified if
+ properties of its colormap are changed. Therefore, an explicit
+ call `~.ContourSet.changed()` is needed after modifying the
+ colormap. The explicit call can be left out, if a colorbar is
+ assigned to the `.QuadContourSet` because it internally calls
+ `~.ContourSet.changed()`.
+
+ Example::
+
+ x = np.arange(1, 10)
+ y = x.reshape(-1, 1)
+ h = x * y
+
+ cs = plt.contourf(h, levels=[10, 30, 50],
+ colors=['#808080', '#A0A0A0', '#C0C0C0'], extend='both')
+ cs.cmap.set_over('red')
+ cs.cmap.set_under('blue')
+ cs.changed()
+
+xunits, yunits : registered units, optional
+ Override axis units by specifying an instance of a
+ :class:`matplotlib.units.ConversionInterface`.
+
+antialiased : bool, optional
+ Enable antialiasing, overriding the defaults. For
+ filled contours, the default is *False*. For line contours,
+ it is taken from :rc:`lines.antialiased`.
+
+nchunk : int >= 0, optional
+ If 0, no subdivision of the domain. Specify a positive integer to
+ divide the domain into subdomains of *nchunk* by *nchunk* quads.
+ Chunking reduces the maximum length of polygons generated by the
+ contouring algorithm which reduces the rendering workload passed
+ on to the backend and also requires slightly less RAM. It can
+ however introduce rendering artifacts at chunk boundaries depending
+ on the backend, the *antialiased* flag and value of *alpha*.
+
+linewidths : float or array-like, default: :rc:`contour.linewidth`
+ *Only applies to* `.contour`.
+
+ The line width of the contour lines.
+
+ If a number, all levels will be plotted with this linewidth.
+
+ If a sequence, the levels in ascending order will be plotted with
+ the linewidths in the order specified.
+
+ If None, this falls back to :rc:`lines.linewidth`.
+
+linestyles : {*None*, 'solid', 'dashed', 'dashdot', 'dotted'}, optional
+ *Only applies to* `.contour`.
+
+ If *linestyles* is *None*, the default is 'solid' unless the lines are
+ monochrome. In that case, negative contours will instead take their
+ linestyle from the *negative_linestyles* argument.
+
+ *linestyles* can also be an iterable of the above strings specifying a set
+ of linestyles to be used. If this iterable is shorter than the number of
+ contour levels it will be repeated as necessary.
+
+negative_linestyles : {*None*, 'solid', 'dashed', 'dashdot', 'dotted'}, \
+ optional
+ *Only applies to* `.contour`.
+
+ If *linestyles* is *None* and the lines are monochrome, this argument
+ specifies the line style for negative contours.
+
+ If *negative_linestyles* is *None*, the default is taken from
+ :rc:`contour.negative_linestyle`.
+
+ *negative_linestyles* can also be an iterable of the above strings
+ specifying a set of linestyles to be used. If this iterable is shorter than
+ the number of contour levels it will be repeated as necessary.
+
+hatches : list[str], optional
+ *Only applies to* `.contourf`.
+
+ A list of cross hatch patterns to use on the filled areas.
+ If None, no hatching will be added to the contour.
+
+algorithm : {'mpl2005', 'mpl2014', 'serial', 'threaded'}, optional
+ Which contouring algorithm to use to calculate the contour lines and
+ polygons. The algorithms are implemented in
+ `ContourPy `_, consult the
+ `ContourPy documentation `_ for
+ further information.
+
+ The default is taken from :rc:`contour.algorithm`.
+
+clip_path : `~matplotlib.patches.Patch` or `.Path` or `.TransformedPath`
+ Set the clip path. See `~matplotlib.artist.Artist.set_clip_path`.
+
+ .. versionadded:: 3.8
+
+data : indexable object, optional
+ DATA_PARAMETER_PLACEHOLDER
+
+Notes
+-----
+1. `.contourf` differs from the MATLAB version in that it does not draw
+ the polygon edges. To draw edges, add line contours with calls to
+ `.contour`.
+
+2. `.contourf` fills intervals that are closed at the top; that is, for
+ boundaries *z1* and *z2*, the filled region is::
+
+ z1 < Z <= z2
+
+ except for the lowest interval, which is closed on both sides (i.e.
+ it includes the lowest value).
+
+3. `.contour` and `.contourf` use a `marching squares
+ `_ algorithm to
+ compute contour locations. More information can be found in
+ `ContourPy documentation `_.
+""" % _docstring.interpd.params)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/dates.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/dates.py
new file mode 100644
index 0000000000000000000000000000000000000000..511e1c6df6ccbd8747c76f297e0a6c20947cda3a
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/matplotlib/dates.py
@@ -0,0 +1,1840 @@
+"""
+Matplotlib provides sophisticated date plotting capabilities, standing on the
+shoulders of python :mod:`datetime` and the add-on module dateutil_.
+
+By default, Matplotlib uses the units machinery described in
+`~matplotlib.units` to convert `datetime.datetime`, and `numpy.datetime64`
+objects when plotted on an x- or y-axis. The user does not
+need to do anything for dates to be formatted, but dates often have strict
+formatting needs, so this module provides many tick locators and formatters.
+A basic example using `numpy.datetime64` is::
+
+ import numpy as np
+
+ times = np.arange(np.datetime64('2001-01-02'),
+ np.datetime64('2002-02-03'), np.timedelta64(75, 'm'))
+ y = np.random.randn(len(times))
+
+ fig, ax = plt.subplots()
+ ax.plot(times, y)
+
+.. seealso::
+
+ - :doc:`/gallery/text_labels_and_annotations/date`
+ - :doc:`/gallery/ticks/date_concise_formatter`
+ - :doc:`/gallery/ticks/date_demo_convert`
+
+.. _date-format:
+
+Matplotlib date format
+----------------------
+
+Matplotlib represents dates using floating point numbers specifying the number
+of days since a default epoch of 1970-01-01 UTC; for example,
+1970-01-01, 06:00 is the floating point number 0.25. The formatters and
+locators require the use of `datetime.datetime` objects, so only dates between
+year 0001 and 9999 can be represented. Microsecond precision
+is achievable for (approximately) 70 years on either side of the epoch, and
+20 microseconds for the rest of the allowable range of dates (year 0001 to
+9999). The epoch can be changed at import time via `.dates.set_epoch` or
+:rc:`date.epoch` to other dates if necessary; see
+:doc:`/gallery/ticks/date_precision_and_epochs` for a discussion.
+
+.. note::
+
+ Before Matplotlib 3.3, the epoch was 0000-12-31 which lost modern
+ microsecond precision and also made the default axis limit of 0 an invalid
+ datetime. In 3.3 the epoch was changed as above. To convert old
+ ordinal floats to the new epoch, users can do::
+
+ new_ordinal = old_ordinal + mdates.date2num(np.datetime64('0000-12-31'))
+
+
+There are a number of helper functions to convert between :mod:`datetime`
+objects and Matplotlib dates:
+
+.. currentmodule:: matplotlib.dates
+
+.. autosummary::
+ :nosignatures:
+
+ datestr2num
+ date2num
+ num2date
+ num2timedelta
+ drange
+ set_epoch
+ get_epoch
+
+.. note::
+
+ Like Python's `datetime.datetime`, Matplotlib uses the Gregorian calendar
+ for all conversions between dates and floating point numbers. This practice
+ is not universal, and calendar differences can cause confusing
+ differences between what Python and Matplotlib give as the number of days
+ since 0001-01-01 and what other software and databases yield. For
+ example, the US Naval Observatory uses a calendar that switches
+ from Julian to Gregorian in October, 1582. Hence, using their
+ calculator, the number of days between 0001-01-01 and 2006-04-01 is
+ 732403, whereas using the Gregorian calendar via the datetime
+ module we find::
+
+ In [1]: date(2006, 4, 1).toordinal() - date(1, 1, 1).toordinal()
+ Out[1]: 732401
+
+All the Matplotlib date converters, locators and formatters are timezone aware.
+If no explicit timezone is provided, :rc:`timezone` is assumed, provided as a
+string. If you want to use a different timezone, pass the *tz* keyword
+argument of `num2date` to any date tick locators or formatters you create. This
+can be either a `datetime.tzinfo` instance or a string with the timezone name
+that can be parsed by `~dateutil.tz.gettz`.
+
+A wide range of specific and general purpose date tick locators and
+formatters are provided in this module. See
+:mod:`matplotlib.ticker` for general information on tick locators
+and formatters. These are described below.
+
+The dateutil_ module provides additional code to handle date ticking, making it
+easy to place ticks on any kinds of dates. See examples below.
+
+.. _dateutil: https://dateutil.readthedocs.io
+
+.. _date-locators:
+
+Date tick locators
+------------------
+
+Most of the date tick locators can locate single or multiple ticks. For example::
+
+ # import constants for the days of the week
+ from matplotlib.dates import MO, TU, WE, TH, FR, SA, SU
+
+ # tick on Mondays every week
+ loc = WeekdayLocator(byweekday=MO, tz=tz)
+
+ # tick on Mondays and Saturdays
+ loc = WeekdayLocator(byweekday=(MO, SA))
+
+In addition, most of the constructors take an interval argument::
+
+ # tick on Mondays every second week
+ loc = WeekdayLocator(byweekday=MO, interval=2)
+
+The rrule locator allows completely general date ticking::
+
+ # tick every 5th easter
+ rule = rrulewrapper(YEARLY, byeaster=1, interval=5)
+ loc = RRuleLocator(rule)
+
+The available date tick locators are:
+
+* `MicrosecondLocator`: Locate microseconds.
+
+* `SecondLocator`: Locate seconds.
+
+* `MinuteLocator`: Locate minutes.
+
+* `HourLocator`: Locate hours.
+
+* `DayLocator`: Locate specified days of the month.
+
+* `WeekdayLocator`: Locate days of the week, e.g., MO, TU.
+
+* `MonthLocator`: Locate months, e.g., 7 for July.
+
+* `YearLocator`: Locate years that are multiples of base.
+
+* `RRuleLocator`: Locate using a `rrulewrapper`.
+ `rrulewrapper` is a simple wrapper around dateutil_'s `dateutil.rrule`
+ which allow almost arbitrary date tick specifications.
+ See :doc:`rrule example `.
+
+* `AutoDateLocator`: On autoscale, this class picks the best `DateLocator`
+ (e.g., `RRuleLocator`) to set the view limits and the tick locations. If
+ called with ``interval_multiples=True`` it will make ticks line up with
+ sensible multiples of the tick intervals. For example, if the interval is
+ 4 hours, it will pick hours 0, 4, 8, etc. as ticks. This behaviour is not
+ guaranteed by default.
+
+.. _date-formatters:
+
+Date formatters
+---------------
+
+The available date formatters are:
+
+* `AutoDateFormatter`: attempts to figure out the best format to use. This is
+ most useful when used with the `AutoDateLocator`.
+
+* `ConciseDateFormatter`: also attempts to figure out the best format to use,
+ and to make the format as compact as possible while still having complete
+ date information. This is most useful when used with the `AutoDateLocator`.
+
+* `DateFormatter`: use `~datetime.datetime.strftime` format strings.
+"""
+
+import datetime
+import functools
+import logging
+import re
+
+from dateutil.rrule import (rrule, MO, TU, WE, TH, FR, SA, SU, YEARLY,
+ MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY,
+ SECONDLY)
+from dateutil.relativedelta import relativedelta
+import dateutil.parser
+import dateutil.tz
+import numpy as np
+
+import matplotlib as mpl
+from matplotlib import _api, cbook, ticker, units
+
+__all__ = ('datestr2num', 'date2num', 'num2date', 'num2timedelta', 'drange',
+ 'set_epoch', 'get_epoch', 'DateFormatter', 'ConciseDateFormatter',
+ 'AutoDateFormatter', 'DateLocator', 'RRuleLocator',
+ 'AutoDateLocator', 'YearLocator', 'MonthLocator', 'WeekdayLocator',
+ 'DayLocator', 'HourLocator', 'MinuteLocator',
+ 'SecondLocator', 'MicrosecondLocator',
+ 'rrule', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU',
+ 'YEARLY', 'MONTHLY', 'WEEKLY', 'DAILY',
+ 'HOURLY', 'MINUTELY', 'SECONDLY', 'MICROSECONDLY', 'relativedelta',
+ 'DateConverter', 'ConciseDateConverter', 'rrulewrapper')
+
+
+_log = logging.getLogger(__name__)
+UTC = datetime.timezone.utc
+
+
+def _get_tzinfo(tz=None):
+ """
+ Generate `~datetime.tzinfo` from a string or return `~datetime.tzinfo`.
+ If None, retrieve the preferred timezone from the rcParams dictionary.
+ """
+ tz = mpl._val_or_rc(tz, 'timezone')
+ if tz == 'UTC':
+ return UTC
+ if isinstance(tz, str):
+ tzinfo = dateutil.tz.gettz(tz)
+ if tzinfo is None:
+ raise ValueError(f"{tz} is not a valid timezone as parsed by"
+ " dateutil.tz.gettz.")
+ return tzinfo
+ if isinstance(tz, datetime.tzinfo):
+ return tz
+ raise TypeError(f"tz must be string or tzinfo subclass, not {tz!r}.")
+
+
+# Time-related constants.
+EPOCH_OFFSET = float(datetime.datetime(1970, 1, 1).toordinal())
+# EPOCH_OFFSET is not used by matplotlib
+MICROSECONDLY = SECONDLY + 1
+HOURS_PER_DAY = 24.
+MIN_PER_HOUR = 60.
+SEC_PER_MIN = 60.
+MONTHS_PER_YEAR = 12.
+
+DAYS_PER_WEEK = 7.
+DAYS_PER_MONTH = 30.
+DAYS_PER_YEAR = 365.0
+
+MINUTES_PER_DAY = MIN_PER_HOUR * HOURS_PER_DAY
+
+SEC_PER_HOUR = SEC_PER_MIN * MIN_PER_HOUR
+SEC_PER_DAY = SEC_PER_HOUR * HOURS_PER_DAY
+SEC_PER_WEEK = SEC_PER_DAY * DAYS_PER_WEEK
+
+MUSECONDS_PER_DAY = 1e6 * SEC_PER_DAY
+
+MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY = (
+ MO, TU, WE, TH, FR, SA, SU)
+WEEKDAYS = (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY)
+
+# default epoch: passed to np.datetime64...
+_epoch = None
+
+
+def _reset_epoch_test_example():
+ """
+ Reset the Matplotlib date epoch so it can be set again.
+
+ Only for use in tests and examples.
+ """
+ global _epoch
+ _epoch = None
+
+
+def set_epoch(epoch):
+ """
+ Set the epoch (origin for dates) for datetime calculations.
+
+ The default epoch is :rc:`date.epoch`.
+
+ If microsecond accuracy is desired, the date being plotted needs to be
+ within approximately 70 years of the epoch. Matplotlib internally
+ represents dates as days since the epoch, so floating point dynamic
+ range needs to be within a factor of 2^52.
+
+ `~.dates.set_epoch` must be called before any dates are converted
+ (i.e. near the import section) or a RuntimeError will be raised.
+
+ See also :doc:`/gallery/ticks/date_precision_and_epochs`.
+
+ Parameters
+ ----------
+ epoch : str
+ valid UTC date parsable by `numpy.datetime64` (do not include
+ timezone).
+
+ """
+ global _epoch
+ if _epoch is not None:
+ raise RuntimeError('set_epoch must be called before dates plotted.')
+ _epoch = epoch
+
+
+def get_epoch():
+ """
+ Get the epoch used by `.dates`.
+
+ Returns
+ -------
+ epoch : str
+ String for the epoch (parsable by `numpy.datetime64`).
+ """
+ global _epoch
+
+ _epoch = mpl._val_or_rc(_epoch, 'date.epoch')
+ return _epoch
+
+
+def _dt64_to_ordinalf(d):
+ """
+ Convert `numpy.datetime64` or an `numpy.ndarray` of those types to
+ Gregorian date as UTC float relative to the epoch (see `.get_epoch`).
+ Roundoff is float64 precision. Practically: microseconds for dates
+ between 290301 BC, 294241 AD, milliseconds for larger dates
+ (see `numpy.datetime64`).
+ """
+
+ # the "extra" ensures that we at least allow the dynamic range out to
+ # seconds. That should get out to +/-2e11 years.
+ dseconds = d.astype('datetime64[s]')
+ extra = (d - dseconds).astype('timedelta64[ns]')
+ t0 = np.datetime64(get_epoch(), 's')
+ dt = (dseconds - t0).astype(np.float64)
+ dt += extra.astype(np.float64) / 1.0e9
+ dt = dt / SEC_PER_DAY
+
+ NaT_int = np.datetime64('NaT').astype(np.int64)
+ d_int = d.astype(np.int64)
+ dt[d_int == NaT_int] = np.nan
+ return dt
+
+
+def _from_ordinalf(x, tz=None):
+ """
+ Convert Gregorian float of the date, preserving hours, minutes,
+ seconds and microseconds. Return value is a `.datetime`.
+
+ The input date *x* is a float in ordinal days at UTC, and the output will
+ be the specified `.datetime` object corresponding to that time in
+ timezone *tz*, or if *tz* is ``None``, in the timezone specified in
+ :rc:`timezone`.
+ """
+
+ tz = _get_tzinfo(tz)
+
+ dt = (np.datetime64(get_epoch()) +
+ np.timedelta64(int(np.round(x * MUSECONDS_PER_DAY)), 'us'))
+ if dt < np.datetime64('0001-01-01') or dt >= np.datetime64('10000-01-01'):
+ raise ValueError(f'Date ordinal {x} converts to {dt} (using '
+ f'epoch {get_epoch()}), but Matplotlib dates must be '
+ 'between year 0001 and 9999.')
+ # convert from datetime64 to datetime:
+ dt = dt.tolist()
+
+ # datetime64 is always UTC:
+ dt = dt.replace(tzinfo=dateutil.tz.gettz('UTC'))
+ # but maybe we are working in a different timezone so move.
+ dt = dt.astimezone(tz)
+ # fix round off errors
+ if np.abs(x) > 70 * 365:
+ # if x is big, round off to nearest twenty microseconds.
+ # This avoids floating point roundoff error
+ ms = round(dt.microsecond / 20) * 20
+ if ms == 1000000:
+ dt = dt.replace(microsecond=0) + datetime.timedelta(seconds=1)
+ else:
+ dt = dt.replace(microsecond=ms)
+
+ return dt
+
+
+# a version of _from_ordinalf that can operate on numpy arrays
+_from_ordinalf_np_vectorized = np.vectorize(_from_ordinalf, otypes="O")
+# a version of dateutil.parser.parse that can operate on numpy arrays
+_dateutil_parser_parse_np_vectorized = np.vectorize(dateutil.parser.parse)
+
+
+def datestr2num(d, default=None):
+ """
+ Convert a date string to a datenum using `dateutil.parser.parse`.
+
+ Parameters
+ ----------
+ d : str or sequence of str
+ The dates to convert.
+
+ default : datetime.datetime, optional
+ The default date to use when fields are missing in *d*.
+ """
+ if isinstance(d, str):
+ dt = dateutil.parser.parse(d, default=default)
+ return date2num(dt)
+ else:
+ if default is not None:
+ d = [date2num(dateutil.parser.parse(s, default=default))
+ for s in d]
+ return np.asarray(d)
+ d = np.asarray(d)
+ if not d.size:
+ return d
+ return date2num(_dateutil_parser_parse_np_vectorized(d))
+
+
+def date2num(d):
+ """
+ Convert datetime objects to Matplotlib dates.
+
+ Parameters
+ ----------
+ d : `datetime.datetime` or `numpy.datetime64` or sequences of these
+
+ Returns
+ -------
+ float or sequence of floats
+ Number of days since the epoch. See `.get_epoch` for the
+ epoch, which can be changed by :rc:`date.epoch` or `.set_epoch`. If
+ the epoch is "1970-01-01T00:00:00" (default) then noon Jan 1 1970
+ ("1970-01-01T12:00:00") returns 0.5.
+
+ Notes
+ -----
+ The Gregorian calendar is assumed; this is not universal practice.
+ For details see the module docstring.
+ """
+ # Unpack in case of e.g. Pandas or xarray object
+ d = cbook._unpack_to_numpy(d)
+
+ # make an iterable, but save state to unpack later:
+ iterable = np.iterable(d)
+ if not iterable:
+ d = [d]
+
+ masked = np.ma.is_masked(d)
+ mask = np.ma.getmask(d)
+ d = np.asarray(d)
+
+ # convert to datetime64 arrays, if not already:
+ if not np.issubdtype(d.dtype, np.datetime64):
+ # datetime arrays
+ if not d.size:
+ # deals with an empty array...
+ return d
+ tzi = getattr(d[0], 'tzinfo', None)
+ if tzi is not None:
+ # make datetime naive:
+ d = [dt.astimezone(UTC).replace(tzinfo=None) for dt in d]
+ d = np.asarray(d)
+ d = d.astype('datetime64[us]')
+
+ d = np.ma.masked_array(d, mask=mask) if masked else d
+ d = _dt64_to_ordinalf(d)
+
+ return d if iterable else d[0]
+
+
+def num2date(x, tz=None):
+ """
+ Convert Matplotlib dates to `~datetime.datetime` objects.
+
+ Parameters
+ ----------
+ x : float or sequence of floats
+ Number of days (fraction part represents hours, minutes, seconds)
+ since the epoch. See `.get_epoch` for the
+ epoch, which can be changed by :rc:`date.epoch` or `.set_epoch`.
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Timezone of *x*. If a string, *tz* is passed to `dateutil.tz`.
+
+ Returns
+ -------
+ `~datetime.datetime` or sequence of `~datetime.datetime`
+ Dates are returned in timezone *tz*.
+
+ If *x* is a sequence, a sequence of `~datetime.datetime` objects will
+ be returned.
+
+ Notes
+ -----
+ The Gregorian calendar is assumed; this is not universal practice.
+ For details, see the module docstring.
+ """
+ tz = _get_tzinfo(tz)
+ return _from_ordinalf_np_vectorized(x, tz).tolist()
+
+
+_ordinalf_to_timedelta_np_vectorized = np.vectorize(
+ lambda x: datetime.timedelta(days=x), otypes="O")
+
+
+def num2timedelta(x):
+ """
+ Convert number of days to a `~datetime.timedelta` object.
+
+ If *x* is a sequence, a sequence of `~datetime.timedelta` objects will
+ be returned.
+
+ Parameters
+ ----------
+ x : float, sequence of floats
+ Number of days. The fraction part represents hours, minutes, seconds.
+
+ Returns
+ -------
+ `datetime.timedelta` or list[`datetime.timedelta`]
+ """
+ return _ordinalf_to_timedelta_np_vectorized(x).tolist()
+
+
+def drange(dstart, dend, delta):
+ """
+ Return a sequence of equally spaced Matplotlib dates.
+
+ The dates start at *dstart* and reach up to, but not including *dend*.
+ They are spaced by *delta*.
+
+ Parameters
+ ----------
+ dstart, dend : `~datetime.datetime`
+ The date limits.
+ delta : `datetime.timedelta`
+ Spacing of the dates.
+
+ Returns
+ -------
+ `numpy.array`
+ A list floats representing Matplotlib dates.
+
+ """
+ f1 = date2num(dstart)
+ f2 = date2num(dend)
+ step = delta.total_seconds() / SEC_PER_DAY
+
+ # calculate the difference between dend and dstart in times of delta
+ num = int(np.ceil((f2 - f1) / step))
+
+ # calculate end of the interval which will be generated
+ dinterval_end = dstart + num * delta
+
+ # ensure, that an half open interval will be generated [dstart, dend)
+ if dinterval_end >= dend:
+ # if the endpoint is greater than or equal to dend,
+ # just subtract one delta
+ dinterval_end -= delta
+ num -= 1
+
+ f2 = date2num(dinterval_end) # new float-endpoint
+ return np.linspace(f1, f2, num + 1)
+
+
+def _wrap_in_tex(text):
+ p = r'([a-zA-Z]+)'
+ ret_text = re.sub(p, r'}$\1$\\mathdefault{', text)
+
+ # Braces ensure symbols are not spaced like binary operators.
+ ret_text = ret_text.replace('-', '{-}').replace(':', '{:}')
+ # To not concatenate space between numbers.
+ ret_text = ret_text.replace(' ', r'\;')
+ ret_text = '$\\mathdefault{' + ret_text + '}$'
+ ret_text = ret_text.replace('$\\mathdefault{}$', '')
+ return ret_text
+
+
+## date tick locators and formatters ###
+
+
+class DateFormatter(ticker.Formatter):
+ """
+ Format a tick (in days since the epoch) with a
+ `~datetime.datetime.strftime` format string.
+ """
+
+ def __init__(self, fmt, tz=None, *, usetex=None):
+ """
+ Parameters
+ ----------
+ fmt : str
+ `~datetime.datetime.strftime` format string
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
+ usetex : bool, default: :rc:`text.usetex`
+ To enable/disable the use of TeX's math mode for rendering the
+ results of the formatter.
+ """
+ self.tz = _get_tzinfo(tz)
+ self.fmt = fmt
+ self._usetex = mpl._val_or_rc(usetex, 'text.usetex')
+
+ def __call__(self, x, pos=0):
+ result = num2date(x, self.tz).strftime(self.fmt)
+ return _wrap_in_tex(result) if self._usetex else result
+
+ def set_tzinfo(self, tz):
+ self.tz = _get_tzinfo(tz)
+
+
+class ConciseDateFormatter(ticker.Formatter):
+ """
+ A `.Formatter` which attempts to figure out the best format to use for the
+ date, and to make it as compact as possible, but still be complete. This is
+ most useful when used with the `AutoDateLocator`::
+
+ >>> locator = AutoDateLocator()
+ >>> formatter = ConciseDateFormatter(locator)
+
+ Parameters
+ ----------
+ locator : `.ticker.Locator`
+ Locator that this axis is using.
+
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone, passed to `.dates.num2date`.
+
+ formats : list of 6 strings, optional
+ Format strings for 6 levels of tick labelling: mostly years,
+ months, days, hours, minutes, and seconds. Strings use
+ the same format codes as `~datetime.datetime.strftime`. Default is
+ ``['%Y', '%b', '%d', '%H:%M', '%H:%M', '%S.%f']``
+
+ zero_formats : list of 6 strings, optional
+ Format strings for tick labels that are "zeros" for a given tick
+ level. For instance, if most ticks are months, ticks around 1 Jan 2005
+ will be labeled "Dec", "2005", "Feb". The default is
+ ``['', '%Y', '%b', '%b-%d', '%H:%M', '%H:%M']``
+
+ offset_formats : list of 6 strings, optional
+ Format strings for the 6 levels that is applied to the "offset"
+ string found on the right side of an x-axis, or top of a y-axis.
+ Combined with the tick labels this should completely specify the
+ date. The default is::
+
+ ['', '%Y', '%Y-%b', '%Y-%b-%d', '%Y-%b-%d', '%Y-%b-%d %H:%M']
+
+ show_offset : bool, default: True
+ Whether to show the offset or not.
+
+ usetex : bool, default: :rc:`text.usetex`
+ To enable/disable the use of TeX's math mode for rendering the results
+ of the formatter.
+
+ Examples
+ --------
+ See :doc:`/gallery/ticks/date_concise_formatter`
+
+ .. plot::
+
+ import datetime
+ import matplotlib.dates as mdates
+
+ base = datetime.datetime(2005, 2, 1)
+ dates = np.array([base + datetime.timedelta(hours=(2 * i))
+ for i in range(732)])
+ N = len(dates)
+ np.random.seed(19680801)
+ y = np.cumsum(np.random.randn(N))
+
+ fig, ax = plt.subplots(constrained_layout=True)
+ locator = mdates.AutoDateLocator()
+ formatter = mdates.ConciseDateFormatter(locator)
+ ax.xaxis.set_major_locator(locator)
+ ax.xaxis.set_major_formatter(formatter)
+
+ ax.plot(dates, y)
+ ax.set_title('Concise Date Formatter')
+
+ """
+
+ def __init__(self, locator, tz=None, formats=None, offset_formats=None,
+ zero_formats=None, show_offset=True, *, usetex=None):
+ """
+ Autoformat the date labels. The default format is used to form an
+ initial string, and then redundant elements are removed.
+ """
+ self._locator = locator
+ self._tz = tz
+ self.defaultfmt = '%Y'
+ # there are 6 levels with each level getting a specific format
+ # 0: mostly years, 1: months, 2: days,
+ # 3: hours, 4: minutes, 5: seconds
+ if formats:
+ if len(formats) != 6:
+ raise ValueError('formats argument must be a list of '
+ '6 format strings (or None)')
+ self.formats = formats
+ else:
+ self.formats = ['%Y', # ticks are mostly years
+ '%b', # ticks are mostly months
+ '%d', # ticks are mostly days
+ '%H:%M', # hrs
+ '%H:%M', # min
+ '%S.%f', # secs
+ ]
+ # fmt for zeros ticks at this level. These are
+ # ticks that should be labeled w/ info the level above.
+ # like 1 Jan can just be labelled "Jan". 02:02:00 can
+ # just be labeled 02:02.
+ if zero_formats:
+ if len(zero_formats) != 6:
+ raise ValueError('zero_formats argument must be a list of '
+ '6 format strings (or None)')
+ self.zero_formats = zero_formats
+ elif formats:
+ # use the users formats for the zero tick formats
+ self.zero_formats = [''] + self.formats[:-1]
+ else:
+ # make the defaults a bit nicer:
+ self.zero_formats = [''] + self.formats[:-1]
+ self.zero_formats[3] = '%b-%d'
+
+ if offset_formats:
+ if len(offset_formats) != 6:
+ raise ValueError('offset_formats argument must be a list of '
+ '6 format strings (or None)')
+ self.offset_formats = offset_formats
+ else:
+ self.offset_formats = ['',
+ '%Y',
+ '%Y-%b',
+ '%Y-%b-%d',
+ '%Y-%b-%d',
+ '%Y-%b-%d %H:%M']
+ self.offset_string = ''
+ self.show_offset = show_offset
+ self._usetex = mpl._val_or_rc(usetex, 'text.usetex')
+
+ def __call__(self, x, pos=None):
+ formatter = DateFormatter(self.defaultfmt, self._tz,
+ usetex=self._usetex)
+ return formatter(x, pos=pos)
+
+ def format_ticks(self, values):
+ tickdatetime = [num2date(value, tz=self._tz) for value in values]
+ tickdate = np.array([tdt.timetuple()[:6] for tdt in tickdatetime])
+
+ # basic algorithm:
+ # 1) only display a part of the date if it changes over the ticks.
+ # 2) don't display the smaller part of the date if:
+ # it is always the same or if it is the start of the
+ # year, month, day etc.
+ # fmt for most ticks at this level
+ fmts = self.formats
+ # format beginnings of days, months, years, etc.
+ zerofmts = self.zero_formats
+ # offset fmt are for the offset in the upper left of the
+ # or lower right of the axis.
+ offsetfmts = self.offset_formats
+ show_offset = self.show_offset
+
+ # determine the level we will label at:
+ # mostly 0: years, 1: months, 2: days,
+ # 3: hours, 4: minutes, 5: seconds, 6: microseconds
+ for level in range(5, -1, -1):
+ unique = np.unique(tickdate[:, level])
+ if len(unique) > 1:
+ # if 1 is included in unique, the year is shown in ticks
+ if level < 2 and np.any(unique == 1):
+ show_offset = False
+ break
+ elif level == 0:
+ # all tickdate are the same, so only micros might be different
+ # set to the most precise (6: microseconds doesn't exist...)
+ level = 5
+
+ # level is the basic level we will label at.
+ # now loop through and decide the actual ticklabels
+ zerovals = [0, 1, 1, 0, 0, 0, 0]
+ labels = [''] * len(tickdate)
+ for nn in range(len(tickdate)):
+ if level < 5:
+ if tickdate[nn][level] == zerovals[level]:
+ fmt = zerofmts[level]
+ else:
+ fmt = fmts[level]
+ else:
+ # special handling for seconds + microseconds
+ if (tickdatetime[nn].second == tickdatetime[nn].microsecond
+ == 0):
+ fmt = zerofmts[level]
+ else:
+ fmt = fmts[level]
+ labels[nn] = tickdatetime[nn].strftime(fmt)
+
+ # special handling of seconds and microseconds:
+ # strip extra zeros and decimal if possible.
+ # this is complicated by two factors. 1) we have some level-4 strings
+ # here (i.e. 03:00, '0.50000', '1.000') 2) we would like to have the
+ # same number of decimals for each string (i.e. 0.5 and 1.0).
+ if level >= 5:
+ trailing_zeros = min(
+ (len(s) - len(s.rstrip('0')) for s in labels if '.' in s),
+ default=None)
+ if trailing_zeros:
+ for nn in range(len(labels)):
+ if '.' in labels[nn]:
+ labels[nn] = labels[nn][:-trailing_zeros].rstrip('.')
+
+ if show_offset:
+ # set the offset string:
+ if (self._locator.axis and
+ self._locator.axis.__name__ in ('xaxis', 'yaxis')
+ and self._locator.axis.get_inverted()):
+ self.offset_string = tickdatetime[0].strftime(offsetfmts[level])
+ else:
+ self.offset_string = tickdatetime[-1].strftime(offsetfmts[level])
+ if self._usetex:
+ self.offset_string = _wrap_in_tex(self.offset_string)
+ else:
+ self.offset_string = ''
+
+ if self._usetex:
+ return [_wrap_in_tex(l) for l in labels]
+ else:
+ return labels
+
+ def get_offset(self):
+ return self.offset_string
+
+ def format_data_short(self, value):
+ return num2date(value, tz=self._tz).strftime('%Y-%m-%d %H:%M:%S')
+
+
+class AutoDateFormatter(ticker.Formatter):
+ """
+ A `.Formatter` which attempts to figure out the best format to use. This
+ is most useful when used with the `AutoDateLocator`.
+
+ `.AutoDateFormatter` has a ``.scale`` dictionary that maps tick scales (the
+ interval in days between one major tick) to format strings; this dictionary
+ defaults to ::
+
+ self.scaled = {
+ DAYS_PER_YEAR: rcParams['date.autoformatter.year'],
+ DAYS_PER_MONTH: rcParams['date.autoformatter.month'],
+ 1: rcParams['date.autoformatter.day'],
+ 1 / HOURS_PER_DAY: rcParams['date.autoformatter.hour'],
+ 1 / MINUTES_PER_DAY: rcParams['date.autoformatter.minute'],
+ 1 / SEC_PER_DAY: rcParams['date.autoformatter.second'],
+ 1 / MUSECONDS_PER_DAY: rcParams['date.autoformatter.microsecond'],
+ }
+
+ The formatter uses the format string corresponding to the lowest key in
+ the dictionary that is greater or equal to the current scale. Dictionary
+ entries can be customized::
+
+ locator = AutoDateLocator()
+ formatter = AutoDateFormatter(locator)
+ formatter.scaled[1/(24*60)] = '%M:%S' # only show min and sec
+
+ Custom callables can also be used instead of format strings. The following
+ example shows how to use a custom format function to strip trailing zeros
+ from decimal seconds and adds the date to the first ticklabel::
+
+ def my_format_function(x, pos=None):
+ x = matplotlib.dates.num2date(x)
+ if pos == 0:
+ fmt = '%D %H:%M:%S.%f'
+ else:
+ fmt = '%H:%M:%S.%f'
+ label = x.strftime(fmt)
+ label = label.rstrip("0")
+ label = label.rstrip(".")
+ return label
+
+ formatter.scaled[1/(24*60)] = my_format_function
+ """
+
+ # This can be improved by providing some user-level direction on
+ # how to choose the best format (precedence, etc.).
+
+ # Perhaps a 'struct' that has a field for each time-type where a
+ # zero would indicate "don't show" and a number would indicate
+ # "show" with some sort of priority. Same priorities could mean
+ # show all with the same priority.
+
+ # Or more simply, perhaps just a format string for each
+ # possibility...
+
+ def __init__(self, locator, tz=None, defaultfmt='%Y-%m-%d', *,
+ usetex=None):
+ """
+ Autoformat the date labels.
+
+ Parameters
+ ----------
+ locator : `.ticker.Locator`
+ Locator that this axis is using.
+
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
+
+ defaultfmt : str
+ The default format to use if none of the values in ``self.scaled``
+ are greater than the unit returned by ``locator._get_unit()``.
+
+ usetex : bool, default: :rc:`text.usetex`
+ To enable/disable the use of TeX's math mode for rendering the
+ results of the formatter. If any entries in ``self.scaled`` are set
+ as functions, then it is up to the customized function to enable or
+ disable TeX's math mode itself.
+ """
+ self._locator = locator
+ self._tz = tz
+ self.defaultfmt = defaultfmt
+ self._formatter = DateFormatter(self.defaultfmt, tz)
+ rcParams = mpl.rcParams
+ self._usetex = mpl._val_or_rc(usetex, 'text.usetex')
+ self.scaled = {
+ DAYS_PER_YEAR: rcParams['date.autoformatter.year'],
+ DAYS_PER_MONTH: rcParams['date.autoformatter.month'],
+ 1: rcParams['date.autoformatter.day'],
+ 1 / HOURS_PER_DAY: rcParams['date.autoformatter.hour'],
+ 1 / MINUTES_PER_DAY: rcParams['date.autoformatter.minute'],
+ 1 / SEC_PER_DAY: rcParams['date.autoformatter.second'],
+ 1 / MUSECONDS_PER_DAY: rcParams['date.autoformatter.microsecond']
+ }
+
+ def _set_locator(self, locator):
+ self._locator = locator
+
+ def __call__(self, x, pos=None):
+ try:
+ locator_unit_scale = float(self._locator._get_unit())
+ except AttributeError:
+ locator_unit_scale = 1
+ # Pick the first scale which is greater than the locator unit.
+ fmt = next((fmt for scale, fmt in sorted(self.scaled.items())
+ if scale >= locator_unit_scale),
+ self.defaultfmt)
+
+ if isinstance(fmt, str):
+ self._formatter = DateFormatter(fmt, self._tz, usetex=self._usetex)
+ result = self._formatter(x, pos)
+ elif callable(fmt):
+ result = fmt(x, pos)
+ else:
+ raise TypeError(f'Unexpected type passed to {self!r}.')
+
+ return result
+
+
+class rrulewrapper:
+ """
+ A simple wrapper around a `dateutil.rrule` allowing flexible
+ date tick specifications.
+ """
+ def __init__(self, freq, tzinfo=None, **kwargs):
+ """
+ Parameters
+ ----------
+ freq : {YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, SECONDLY}
+ Tick frequency. These constants are defined in `dateutil.rrule`,
+ but they are accessible from `matplotlib.dates` as well.
+ tzinfo : `datetime.tzinfo`, optional
+ Time zone information. The default is None.
+ **kwargs
+ Additional keyword arguments are passed to the `dateutil.rrule`.
+ """
+ kwargs['freq'] = freq
+ self._base_tzinfo = tzinfo
+
+ self._update_rrule(**kwargs)
+
+ def set(self, **kwargs):
+ """Set parameters for an existing wrapper."""
+ self._construct.update(kwargs)
+
+ self._update_rrule(**self._construct)
+
+ def _update_rrule(self, **kwargs):
+ tzinfo = self._base_tzinfo
+
+ # rrule does not play nicely with timezones - especially pytz time
+ # zones, it's best to use naive zones and attach timezones once the
+ # datetimes are returned
+ if 'dtstart' in kwargs:
+ dtstart = kwargs['dtstart']
+ if dtstart.tzinfo is not None:
+ if tzinfo is None:
+ tzinfo = dtstart.tzinfo
+ else:
+ dtstart = dtstart.astimezone(tzinfo)
+
+ kwargs['dtstart'] = dtstart.replace(tzinfo=None)
+
+ if 'until' in kwargs:
+ until = kwargs['until']
+ if until.tzinfo is not None:
+ if tzinfo is not None:
+ until = until.astimezone(tzinfo)
+ else:
+ raise ValueError('until cannot be aware if dtstart '
+ 'is naive and tzinfo is None')
+
+ kwargs['until'] = until.replace(tzinfo=None)
+
+ self._construct = kwargs.copy()
+ self._tzinfo = tzinfo
+ self._rrule = rrule(**self._construct)
+
+ def _attach_tzinfo(self, dt, tzinfo):
+ # pytz zones are attached by "localizing" the datetime
+ if hasattr(tzinfo, 'localize'):
+ return tzinfo.localize(dt, is_dst=True)
+
+ return dt.replace(tzinfo=tzinfo)
+
+ def _aware_return_wrapper(self, f, returns_list=False):
+ """Decorator function that allows rrule methods to handle tzinfo."""
+ # This is only necessary if we're actually attaching a tzinfo
+ if self._tzinfo is None:
+ return f
+
+ # All datetime arguments must be naive. If they are not naive, they are
+ # converted to the _tzinfo zone before dropping the zone.
+ def normalize_arg(arg):
+ if isinstance(arg, datetime.datetime) and arg.tzinfo is not None:
+ if arg.tzinfo is not self._tzinfo:
+ arg = arg.astimezone(self._tzinfo)
+
+ return arg.replace(tzinfo=None)
+
+ return arg
+
+ def normalize_args(args, kwargs):
+ args = tuple(normalize_arg(arg) for arg in args)
+ kwargs = {kw: normalize_arg(arg) for kw, arg in kwargs.items()}
+
+ return args, kwargs
+
+ # There are two kinds of functions we care about - ones that return
+ # dates and ones that return lists of dates.
+ if not returns_list:
+ def inner_func(*args, **kwargs):
+ args, kwargs = normalize_args(args, kwargs)
+ dt = f(*args, **kwargs)
+ return self._attach_tzinfo(dt, self._tzinfo)
+ else:
+ def inner_func(*args, **kwargs):
+ args, kwargs = normalize_args(args, kwargs)
+ dts = f(*args, **kwargs)
+ return [self._attach_tzinfo(dt, self._tzinfo) for dt in dts]
+
+ return functools.wraps(f)(inner_func)
+
+ def __getattr__(self, name):
+ if name in self.__dict__:
+ return self.__dict__[name]
+
+ f = getattr(self._rrule, name)
+
+ if name in {'after', 'before'}:
+ return self._aware_return_wrapper(f)
+ elif name in {'xafter', 'xbefore', 'between'}:
+ return self._aware_return_wrapper(f, returns_list=True)
+ else:
+ return f
+
+ def __setstate__(self, state):
+ self.__dict__.update(state)
+
+
+class DateLocator(ticker.Locator):
+ """
+ Determines the tick locations when plotting dates.
+
+ This class is subclassed by other Locators and
+ is not meant to be used on its own.
+ """
+ hms0d = {'byhour': 0, 'byminute': 0, 'bysecond': 0}
+
+ def __init__(self, tz=None):
+ """
+ Parameters
+ ----------
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
+ """
+ self.tz = _get_tzinfo(tz)
+
+ def set_tzinfo(self, tz):
+ """
+ Set timezone info.
+
+ Parameters
+ ----------
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
+ """
+ self.tz = _get_tzinfo(tz)
+
+ def datalim_to_dt(self):
+ """Convert axis data interval to datetime objects."""
+ dmin, dmax = self.axis.get_data_interval()
+ if dmin > dmax:
+ dmin, dmax = dmax, dmin
+
+ return num2date(dmin, self.tz), num2date(dmax, self.tz)
+
+ def viewlim_to_dt(self):
+ """Convert the view interval to datetime objects."""
+ vmin, vmax = self.axis.get_view_interval()
+ if vmin > vmax:
+ vmin, vmax = vmax, vmin
+ return num2date(vmin, self.tz), num2date(vmax, self.tz)
+
+ def _get_unit(self):
+ """
+ Return how many days a unit of the locator is; used for
+ intelligent autoscaling.
+ """
+ return 1
+
+ def _get_interval(self):
+ """
+ Return the number of units for each tick.
+ """
+ return 1
+
+ def nonsingular(self, vmin, vmax):
+ """
+ Given the proposed upper and lower extent, adjust the range
+ if it is too close to being singular (i.e. a range of ~0).
+ """
+ if not np.isfinite(vmin) or not np.isfinite(vmax):
+ # Except if there is no data, then use 1970 as default.
+ return (date2num(datetime.date(1970, 1, 1)),
+ date2num(datetime.date(1970, 1, 2)))
+ if vmax < vmin:
+ vmin, vmax = vmax, vmin
+ unit = self._get_unit()
+ interval = self._get_interval()
+ if abs(vmax - vmin) < 1e-6:
+ vmin -= 2 * unit * interval
+ vmax += 2 * unit * interval
+ return vmin, vmax
+
+
+class RRuleLocator(DateLocator):
+ # use the dateutil rrule instance
+
+ def __init__(self, o, tz=None):
+ super().__init__(tz)
+ self.rule = o
+
+ def __call__(self):
+ # if no data have been set, this will tank with a ValueError
+ try:
+ dmin, dmax = self.viewlim_to_dt()
+ except ValueError:
+ return []
+
+ return self.tick_values(dmin, dmax)
+
+ def tick_values(self, vmin, vmax):
+ start, stop = self._create_rrule(vmin, vmax)
+ dates = self.rule.between(start, stop, True)
+ if len(dates) == 0:
+ return date2num([vmin, vmax])
+ return self.raise_if_exceeds(date2num(dates))
+
+ def _create_rrule(self, vmin, vmax):
+ # set appropriate rrule dtstart and until and return
+ # start and end
+ delta = relativedelta(vmax, vmin)
+
+ # We need to cap at the endpoints of valid datetime
+ try:
+ start = vmin - delta
+ except (ValueError, OverflowError):
+ # cap
+ start = datetime.datetime(1, 1, 1, 0, 0, 0,
+ tzinfo=datetime.timezone.utc)
+
+ try:
+ stop = vmax + delta
+ except (ValueError, OverflowError):
+ # cap
+ stop = datetime.datetime(9999, 12, 31, 23, 59, 59,
+ tzinfo=datetime.timezone.utc)
+
+ self.rule.set(dtstart=start, until=stop)
+
+ return vmin, vmax
+
+ def _get_unit(self):
+ # docstring inherited
+ freq = self.rule._rrule._freq
+ return self.get_unit_generic(freq)
+
+ @staticmethod
+ def get_unit_generic(freq):
+ if freq == YEARLY:
+ return DAYS_PER_YEAR
+ elif freq == MONTHLY:
+ return DAYS_PER_MONTH
+ elif freq == WEEKLY:
+ return DAYS_PER_WEEK
+ elif freq == DAILY:
+ return 1.0
+ elif freq == HOURLY:
+ return 1.0 / HOURS_PER_DAY
+ elif freq == MINUTELY:
+ return 1.0 / MINUTES_PER_DAY
+ elif freq == SECONDLY:
+ return 1.0 / SEC_PER_DAY
+ else:
+ # error
+ return -1 # or should this just return '1'?
+
+ def _get_interval(self):
+ return self.rule._rrule._interval
+
+
+class AutoDateLocator(DateLocator):
+ """
+ On autoscale, this class picks the best `DateLocator` to set the view
+ limits and the tick locations.
+
+ Attributes
+ ----------
+ intervald : dict
+
+ Mapping of tick frequencies to multiples allowed for that ticking.
+ The default is ::
+
+ self.intervald = {
+ YEARLY : [1, 2, 4, 5, 10, 20, 40, 50, 100, 200, 400, 500,
+ 1000, 2000, 4000, 5000, 10000],
+ MONTHLY : [1, 2, 3, 4, 6],
+ DAILY : [1, 2, 3, 7, 14, 21],
+ HOURLY : [1, 2, 3, 4, 6, 12],
+ MINUTELY: [1, 5, 10, 15, 30],
+ SECONDLY: [1, 5, 10, 15, 30],
+ MICROSECONDLY: [1, 2, 5, 10, 20, 50, 100, 200, 500,
+ 1000, 2000, 5000, 10000, 20000, 50000,
+ 100000, 200000, 500000, 1000000],
+ }
+
+ where the keys are defined in `dateutil.rrule`.
+
+ The interval is used to specify multiples that are appropriate for
+ the frequency of ticking. For instance, every 7 days is sensible
+ for daily ticks, but for minutes/seconds, 15 or 30 make sense.
+
+ When customizing, you should only modify the values for the existing
+ keys. You should not add or delete entries.
+
+ Example for forcing ticks every 3 hours::
+
+ locator = AutoDateLocator()
+ locator.intervald[HOURLY] = [3] # only show every 3 hours
+ """
+
+ def __init__(self, tz=None, minticks=5, maxticks=None,
+ interval_multiples=True):
+ """
+ Parameters
+ ----------
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
+ minticks : int
+ The minimum number of ticks desired; controls whether ticks occur
+ yearly, monthly, etc.
+ maxticks : int
+ The maximum number of ticks desired; controls the interval between
+ ticks (ticking every other, every 3, etc.). For fine-grained
+ control, this can be a dictionary mapping individual rrule
+ frequency constants (YEARLY, MONTHLY, etc.) to their own maximum
+ number of ticks. This can be used to keep the number of ticks
+ appropriate to the format chosen in `AutoDateFormatter`. Any
+ frequency not specified in this dictionary is given a default
+ value.
+ interval_multiples : bool, default: True
+ Whether ticks should be chosen to be multiple of the interval,
+ locking them to 'nicer' locations. For example, this will force
+ the ticks to be at hours 0, 6, 12, 18 when hourly ticking is done
+ at 6 hour intervals.
+ """
+ super().__init__(tz=tz)
+ self._freq = YEARLY
+ self._freqs = [YEARLY, MONTHLY, DAILY, HOURLY, MINUTELY,
+ SECONDLY, MICROSECONDLY]
+ self.minticks = minticks
+
+ self.maxticks = {YEARLY: 11, MONTHLY: 12, DAILY: 11, HOURLY: 12,
+ MINUTELY: 11, SECONDLY: 11, MICROSECONDLY: 8}
+ if maxticks is not None:
+ try:
+ self.maxticks.update(maxticks)
+ except TypeError:
+ # Assume we were given an integer. Use this as the maximum
+ # number of ticks for every frequency and create a
+ # dictionary for this
+ self.maxticks = dict.fromkeys(self._freqs, maxticks)
+ self.interval_multiples = interval_multiples
+ self.intervald = {
+ YEARLY: [1, 2, 4, 5, 10, 20, 40, 50, 100, 200, 400, 500,
+ 1000, 2000, 4000, 5000, 10000],
+ MONTHLY: [1, 2, 3, 4, 6],
+ DAILY: [1, 2, 3, 7, 14, 21],
+ HOURLY: [1, 2, 3, 4, 6, 12],
+ MINUTELY: [1, 5, 10, 15, 30],
+ SECONDLY: [1, 5, 10, 15, 30],
+ MICROSECONDLY: [1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000,
+ 5000, 10000, 20000, 50000, 100000, 200000, 500000,
+ 1000000],
+ }
+ if interval_multiples:
+ # Swap "3" for "4" in the DAILY list; If we use 3 we get bad
+ # tick loc for months w/ 31 days: 1, 4, ..., 28, 31, 1
+ # If we use 4 then we get: 1, 5, ... 25, 29, 1
+ self.intervald[DAILY] = [1, 2, 4, 7, 14]
+
+ self._byranges = [None, range(1, 13), range(1, 32),
+ range(0, 24), range(0, 60), range(0, 60), None]
+
+ def __call__(self):
+ # docstring inherited
+ dmin, dmax = self.viewlim_to_dt()
+ locator = self.get_locator(dmin, dmax)
+ return locator()
+
+ def tick_values(self, vmin, vmax):
+ return self.get_locator(vmin, vmax).tick_values(vmin, vmax)
+
+ def nonsingular(self, vmin, vmax):
+ # whatever is thrown at us, we can scale the unit.
+ # But default nonsingular date plots at an ~4 year period.
+ if not np.isfinite(vmin) or not np.isfinite(vmax):
+ # Except if there is no data, then use 1970 as default.
+ return (date2num(datetime.date(1970, 1, 1)),
+ date2num(datetime.date(1970, 1, 2)))
+ if vmax < vmin:
+ vmin, vmax = vmax, vmin
+ if vmin == vmax:
+ vmin = vmin - DAYS_PER_YEAR * 2
+ vmax = vmax + DAYS_PER_YEAR * 2
+ return vmin, vmax
+
+ def _get_unit(self):
+ if self._freq in [MICROSECONDLY]:
+ return 1. / MUSECONDS_PER_DAY
+ else:
+ return RRuleLocator.get_unit_generic(self._freq)
+
+ def get_locator(self, dmin, dmax):
+ """Pick the best locator based on a distance."""
+ delta = relativedelta(dmax, dmin)
+ tdelta = dmax - dmin
+
+ # take absolute difference
+ if dmin > dmax:
+ delta = -delta
+ tdelta = -tdelta
+ # The following uses a mix of calls to relativedelta and timedelta
+ # methods because there is incomplete overlap in the functionality of
+ # these similar functions, and it's best to avoid doing our own math
+ # whenever possible.
+ numYears = float(delta.years)
+ numMonths = numYears * MONTHS_PER_YEAR + delta.months
+ numDays = tdelta.days # Avoids estimates of days/month, days/year.
+ numHours = numDays * HOURS_PER_DAY + delta.hours
+ numMinutes = numHours * MIN_PER_HOUR + delta.minutes
+ numSeconds = np.floor(tdelta.total_seconds())
+ numMicroseconds = np.floor(tdelta.total_seconds() * 1e6)
+
+ nums = [numYears, numMonths, numDays, numHours, numMinutes,
+ numSeconds, numMicroseconds]
+
+ use_rrule_locator = [True] * 6 + [False]
+
+ # Default setting of bymonth, etc. to pass to rrule
+ # [unused (for year), bymonth, bymonthday, byhour, byminute,
+ # bysecond, unused (for microseconds)]
+ byranges = [None, 1, 1, 0, 0, 0, None]
+
+ # Loop over all the frequencies and try to find one that gives at
+ # least a minticks tick positions. Once this is found, look for
+ # an interval from a list specific to that frequency that gives no
+ # more than maxticks tick positions. Also, set up some ranges
+ # (bymonth, etc.) as appropriate to be passed to rrulewrapper.
+ for i, (freq, num) in enumerate(zip(self._freqs, nums)):
+ # If this particular frequency doesn't give enough ticks, continue
+ if num < self.minticks:
+ # Since we're not using this particular frequency, set
+ # the corresponding by_ to None so the rrule can act as
+ # appropriate
+ byranges[i] = None
+ continue
+
+ # Find the first available interval that doesn't give too many
+ # ticks
+ for interval in self.intervald[freq]:
+ if num <= interval * (self.maxticks[freq] - 1):
+ break
+ else:
+ if not (self.interval_multiples and freq == DAILY):
+ _api.warn_external(
+ f"AutoDateLocator was unable to pick an appropriate "
+ f"interval for this date range. It may be necessary "
+ f"to add an interval value to the AutoDateLocator's "
+ f"intervald dictionary. Defaulting to {interval}.")
+
+ # Set some parameters as appropriate
+ self._freq = freq
+
+ if self._byranges[i] and self.interval_multiples:
+ byranges[i] = self._byranges[i][::interval]
+ if i in (DAILY, WEEKLY):
+ if interval == 14:
+ # just make first and 15th. Avoids 30th.
+ byranges[i] = [1, 15]
+ elif interval == 7:
+ byranges[i] = [1, 8, 15, 22]
+
+ interval = 1
+ else:
+ byranges[i] = self._byranges[i]
+ break
+ else:
+ interval = 1
+
+ if (freq == YEARLY) and self.interval_multiples:
+ locator = YearLocator(interval, tz=self.tz)
+ elif use_rrule_locator[i]:
+ _, bymonth, bymonthday, byhour, byminute, bysecond, _ = byranges
+ rrule = rrulewrapper(self._freq, interval=interval,
+ dtstart=dmin, until=dmax,
+ bymonth=bymonth, bymonthday=bymonthday,
+ byhour=byhour, byminute=byminute,
+ bysecond=bysecond)
+
+ locator = RRuleLocator(rrule, tz=self.tz)
+ else:
+ locator = MicrosecondLocator(interval, tz=self.tz)
+ if date2num(dmin) > 70 * 365 and interval < 1000:
+ _api.warn_external(
+ 'Plotting microsecond time intervals for dates far from '
+ f'the epoch (time origin: {get_epoch()}) is not well-'
+ 'supported. See matplotlib.dates.set_epoch to change the '
+ 'epoch.')
+
+ locator.set_axis(self.axis)
+ return locator
+
+
+class YearLocator(RRuleLocator):
+ """
+ Make ticks on a given day of each year that is a multiple of base.
+
+ Examples::
+
+ # Tick every year on Jan 1st
+ locator = YearLocator()
+
+ # Tick every 5 years on July 4th
+ locator = YearLocator(5, month=7, day=4)
+ """
+ def __init__(self, base=1, month=1, day=1, tz=None):
+ """
+ Parameters
+ ----------
+ base : int, default: 1
+ Mark ticks every *base* years.
+ month : int, default: 1
+ The month on which to place the ticks, starting from 1. Default is
+ January.
+ day : int, default: 1
+ The day on which to place the ticks.
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
+ """
+ rule = rrulewrapper(YEARLY, interval=base, bymonth=month,
+ bymonthday=day, **self.hms0d)
+ super().__init__(rule, tz=tz)
+ self.base = ticker._Edge_integer(base, 0)
+
+ def _create_rrule(self, vmin, vmax):
+ # 'start' needs to be a multiple of the interval to create ticks on
+ # interval multiples when the tick frequency is YEARLY
+ ymin = max(self.base.le(vmin.year) * self.base.step, 1)
+ ymax = min(self.base.ge(vmax.year) * self.base.step, 9999)
+
+ c = self.rule._construct
+ replace = {'year': ymin,
+ 'month': c.get('bymonth', 1),
+ 'day': c.get('bymonthday', 1),
+ 'hour': 0, 'minute': 0, 'second': 0}
+
+ start = vmin.replace(**replace)
+ stop = start.replace(year=ymax)
+ self.rule.set(dtstart=start, until=stop)
+
+ return start, stop
+
+
+class MonthLocator(RRuleLocator):
+ """
+ Make ticks on occurrences of each month, e.g., 1, 3, 12.
+ """
+ def __init__(self, bymonth=None, bymonthday=1, interval=1, tz=None):
+ """
+ Parameters
+ ----------
+ bymonth : int or list of int, default: all months
+ Ticks will be placed on every month in *bymonth*. Default is
+ ``range(1, 13)``, i.e. every month.
+ bymonthday : int, default: 1
+ The day on which to place the ticks.
+ interval : int, default: 1
+ The interval between each iteration. For example, if
+ ``interval=2``, mark every second occurrence.
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
+ """
+ if bymonth is None:
+ bymonth = range(1, 13)
+
+ rule = rrulewrapper(MONTHLY, bymonth=bymonth, bymonthday=bymonthday,
+ interval=interval, **self.hms0d)
+ super().__init__(rule, tz=tz)
+
+
+class WeekdayLocator(RRuleLocator):
+ """
+ Make ticks on occurrences of each weekday.
+ """
+
+ def __init__(self, byweekday=1, interval=1, tz=None):
+ """
+ Parameters
+ ----------
+ byweekday : int or list of int, default: all days
+ Ticks will be placed on every weekday in *byweekday*. Default is
+ every day.
+
+ Elements of *byweekday* must be one of MO, TU, WE, TH, FR, SA,
+ SU, the constants from :mod:`dateutil.rrule`, which have been
+ imported into the :mod:`matplotlib.dates` namespace.
+ interval : int, default: 1
+ The interval between each iteration. For example, if
+ ``interval=2``, mark every second occurrence.
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
+ """
+ rule = rrulewrapper(DAILY, byweekday=byweekday,
+ interval=interval, **self.hms0d)
+ super().__init__(rule, tz=tz)
+
+
+class DayLocator(RRuleLocator):
+ """
+ Make ticks on occurrences of each day of the month. For example,
+ 1, 15, 30.
+ """
+ def __init__(self, bymonthday=None, interval=1, tz=None):
+ """
+ Parameters
+ ----------
+ bymonthday : int or list of int, default: all days
+ Ticks will be placed on every day in *bymonthday*. Default is
+ ``bymonthday=range(1, 32)``, i.e., every day of the month.
+ interval : int, default: 1
+ The interval between each iteration. For example, if
+ ``interval=2``, mark every second occurrence.
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
+ """
+ if interval != int(interval) or interval < 1:
+ raise ValueError("interval must be an integer greater than 0")
+ if bymonthday is None:
+ bymonthday = range(1, 32)
+
+ rule = rrulewrapper(DAILY, bymonthday=bymonthday,
+ interval=interval, **self.hms0d)
+ super().__init__(rule, tz=tz)
+
+
+class HourLocator(RRuleLocator):
+ """
+ Make ticks on occurrences of each hour.
+ """
+ def __init__(self, byhour=None, interval=1, tz=None):
+ """
+ Parameters
+ ----------
+ byhour : int or list of int, default: all hours
+ Ticks will be placed on every hour in *byhour*. Default is
+ ``byhour=range(24)``, i.e., every hour.
+ interval : int, default: 1
+ The interval between each iteration. For example, if
+ ``interval=2``, mark every second occurrence.
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
+ """
+ if byhour is None:
+ byhour = range(24)
+
+ rule = rrulewrapper(HOURLY, byhour=byhour, interval=interval,
+ byminute=0, bysecond=0)
+ super().__init__(rule, tz=tz)
+
+
+class MinuteLocator(RRuleLocator):
+ """
+ Make ticks on occurrences of each minute.
+ """
+ def __init__(self, byminute=None, interval=1, tz=None):
+ """
+ Parameters
+ ----------
+ byminute : int or list of int, default: all minutes
+ Ticks will be placed on every minute in *byminute*. Default is
+ ``byminute=range(60)``, i.e., every minute.
+ interval : int, default: 1
+ The interval between each iteration. For example, if
+ ``interval=2``, mark every second occurrence.
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
+ """
+ if byminute is None:
+ byminute = range(60)
+
+ rule = rrulewrapper(MINUTELY, byminute=byminute, interval=interval,
+ bysecond=0)
+ super().__init__(rule, tz=tz)
+
+
+class SecondLocator(RRuleLocator):
+ """
+ Make ticks on occurrences of each second.
+ """
+ def __init__(self, bysecond=None, interval=1, tz=None):
+ """
+ Parameters
+ ----------
+ bysecond : int or list of int, default: all seconds
+ Ticks will be placed on every second in *bysecond*. Default is
+ ``bysecond = range(60)``, i.e., every second.
+ interval : int, default: 1
+ The interval between each iteration. For example, if
+ ``interval=2``, mark every second occurrence.
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
+ """
+ if bysecond is None:
+ bysecond = range(60)
+
+ rule = rrulewrapper(SECONDLY, bysecond=bysecond, interval=interval)
+ super().__init__(rule, tz=tz)
+
+
+class MicrosecondLocator(DateLocator):
+ """
+ Make ticks on regular intervals of one or more microsecond(s).
+
+ .. note::
+
+ By default, Matplotlib uses a floating point representation of time in
+ days since the epoch, so plotting data with
+ microsecond time resolution does not work well for
+ dates that are far (about 70 years) from the epoch (check with
+ `~.dates.get_epoch`).
+
+ If you want sub-microsecond resolution time plots, it is strongly
+ recommended to use floating point seconds, not datetime-like
+ time representation.
+
+ If you really must use datetime.datetime() or similar and still
+ need microsecond precision, change the time origin via
+ `.dates.set_epoch` to something closer to the dates being plotted.
+ See :doc:`/gallery/ticks/date_precision_and_epochs`.
+
+ """
+ def __init__(self, interval=1, tz=None):
+ """
+ Parameters
+ ----------
+ interval : int, default: 1
+ The interval between each iteration. For example, if
+ ``interval=2``, mark every second occurrence.
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
+ """
+ super().__init__(tz=tz)
+ self._interval = interval
+ self._wrapped_locator = ticker.MultipleLocator(interval)
+
+ def set_axis(self, axis):
+ self._wrapped_locator.set_axis(axis)
+ return super().set_axis(axis)
+
+ def __call__(self):
+ # if no data have been set, this will tank with a ValueError
+ try:
+ dmin, dmax = self.viewlim_to_dt()
+ except ValueError:
+ return []
+
+ return self.tick_values(dmin, dmax)
+
+ def tick_values(self, vmin, vmax):
+ nmin, nmax = date2num((vmin, vmax))
+ t0 = np.floor(nmin)
+ nmax = nmax - t0
+ nmin = nmin - t0
+ nmin *= MUSECONDS_PER_DAY
+ nmax *= MUSECONDS_PER_DAY
+
+ ticks = self._wrapped_locator.tick_values(nmin, nmax)
+
+ ticks = ticks / MUSECONDS_PER_DAY + t0
+ return ticks
+
+ def _get_unit(self):
+ # docstring inherited
+ return 1. / MUSECONDS_PER_DAY
+
+ def _get_interval(self):
+ # docstring inherited
+ return self._interval
+
+
+class DateConverter(units.ConversionInterface):
+ """
+ Converter for `datetime.date` and `datetime.datetime` data, or for
+ date/time data represented as it would be converted by `date2num`.
+
+ The 'unit' tag for such data is None or a `~datetime.tzinfo` instance.
+ """
+
+ def __init__(self, *, interval_multiples=True):
+ self._interval_multiples = interval_multiples
+ super().__init__()
+
+ def axisinfo(self, unit, axis):
+ """
+ Return the `~matplotlib.units.AxisInfo` for *unit*.
+
+ *unit* is a `~datetime.tzinfo` instance or None.
+ The *axis* argument is required but not used.
+ """
+ tz = unit
+
+ majloc = AutoDateLocator(tz=tz,
+ interval_multiples=self._interval_multiples)
+ majfmt = AutoDateFormatter(majloc, tz=tz)
+ datemin = datetime.date(1970, 1, 1)
+ datemax = datetime.date(1970, 1, 2)
+
+ return units.AxisInfo(majloc=majloc, majfmt=majfmt, label='',
+ default_limits=(datemin, datemax))
+
+ @staticmethod
+ def convert(value, unit, axis):
+ """
+ If *value* is not already a number or sequence of numbers, convert it
+ with `date2num`.
+
+ The *unit* and *axis* arguments are not used.
+ """
+ return date2num(value)
+
+ @staticmethod
+ def default_units(x, axis):
+ """
+ Return the `~datetime.tzinfo` instance of *x* or of its first element,
+ or None
+ """
+ if isinstance(x, np.ndarray):
+ x = x.ravel()
+
+ try:
+ x = cbook._safe_first_finite(x)
+ except (TypeError, StopIteration):
+ pass
+
+ try:
+ return x.tzinfo
+ except AttributeError:
+ pass
+ return None
+
+
+class ConciseDateConverter(DateConverter):
+ # docstring inherited
+
+ def __init__(self, formats=None, zero_formats=None, offset_formats=None,
+ show_offset=True, *, interval_multiples=True):
+ self._formats = formats
+ self._zero_formats = zero_formats
+ self._offset_formats = offset_formats
+ self._show_offset = show_offset
+ self._interval_multiples = interval_multiples
+ super().__init__()
+
+ def axisinfo(self, unit, axis):
+ # docstring inherited
+ tz = unit
+ majloc = AutoDateLocator(tz=tz,
+ interval_multiples=self._interval_multiples)
+ majfmt = ConciseDateFormatter(majloc, tz=tz, formats=self._formats,
+ zero_formats=self._zero_formats,
+ offset_formats=self._offset_formats,
+ show_offset=self._show_offset)
+ datemin = datetime.date(1970, 1, 1)
+ datemax = datetime.date(1970, 1, 2)
+ return units.AxisInfo(majloc=majloc, majfmt=majfmt, label='',
+ default_limits=(datemin, datemax))
+
+
+class _SwitchableDateConverter:
+ """
+ Helper converter-like object that generates and dispatches to
+ temporary ConciseDateConverter or DateConverter instances based on
+ :rc:`date.converter` and :rc:`date.interval_multiples`.
+ """
+
+ @staticmethod
+ def _get_converter():
+ converter_cls = {
+ "concise": ConciseDateConverter, "auto": DateConverter}[
+ mpl.rcParams["date.converter"]]
+ interval_multiples = mpl.rcParams["date.interval_multiples"]
+ return converter_cls(interval_multiples=interval_multiples)
+
+ def axisinfo(self, *args, **kwargs):
+ return self._get_converter().axisinfo(*args, **kwargs)
+
+ def default_units(self, *args, **kwargs):
+ return self._get_converter().default_units(*args, **kwargs)
+
+ def convert(self, *args, **kwargs):
+ return self._get_converter().convert(*args, **kwargs)
+
+
+units.registry[np.datetime64] = \
+ units.registry[datetime.date] = \
+ units.registry[datetime.datetime] = \
+ _SwitchableDateConverter()
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/__pycache__/__config__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/__pycache__/__config__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e343405a9145db36403d8479efa5032d9062190f
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/__pycache__/__config__.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..35b4cdb97ebfc0ae36fd4424767cdd80fe3a8cc9
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/__pycache__/_array_api_info.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/__pycache__/_array_api_info.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e54789efe31ab6fb4e428cbf0957e138e5906dd5
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/__pycache__/_array_api_info.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/__pycache__/_distributor_init.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/__pycache__/_distributor_init.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e8536f28abce5d595f443168a5a79ffdf2d170c9
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/__pycache__/_distributor_init.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/__pycache__/_expired_attrs_2_0.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/__pycache__/_expired_attrs_2_0.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d4367c83c4f887d5b5262839e2a9ec68b8dce9d8
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/__pycache__/_expired_attrs_2_0.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/__pycache__/_globals.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/__pycache__/_globals.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e0c1988e42a0cdf63d2ace40b87fc7354df731e0
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/__pycache__/_globals.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/__pycache__/_pytesttester.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/__pycache__/_pytesttester.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..adb9b5324cb853e00ae4e8b9b7bab0845ccef690
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/__pycache__/_pytesttester.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/__pycache__/ctypeslib.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/__pycache__/ctypeslib.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fe1071048acd0e2d4df6ae2a7b863640eec9a772
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/__pycache__/ctypeslib.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/__pycache__/dtypes.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/__pycache__/dtypes.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..79d71f2b22d70174046419675b75fbdde880a008
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/__pycache__/dtypes.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/__pycache__/exceptions.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/__pycache__/exceptions.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8ffdcc7b0e8fa79b07cb81135e9dee7fe2a6c967
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/__pycache__/exceptions.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/__pycache__/version.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/__pycache__/version.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ca0e6e9422b4eadd13a12d809292561e0ad2b85a
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/__pycache__/version.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4b90877138a3ae5e06f35eb668200931073f394b
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__init__.py
@@ -0,0 +1,180 @@
+"""
+Contains the core of NumPy: ndarray, ufuncs, dtypes, etc.
+
+Please note that this module is private. All functions and objects
+are available in the main ``numpy`` namespace - use that instead.
+
+"""
+
+import os
+
+from numpy.version import version as __version__
+
+
+# disables OpenBLAS affinity setting of the main thread that limits
+# python threads or processes to one core
+env_added = []
+for envkey in ['OPENBLAS_MAIN_FREE', 'GOTOBLAS_MAIN_FREE']:
+ if envkey not in os.environ:
+ os.environ[envkey] = '1'
+ env_added.append(envkey)
+
+try:
+ from . import multiarray
+except ImportError as exc:
+ import sys
+ msg = """
+
+IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!
+
+Importing the numpy C-extensions failed. This error can happen for
+many reasons, often due to issues with your setup or how NumPy was
+installed.
+
+We have compiled some common reasons and troubleshooting tips at:
+
+ https://numpy.org/devdocs/user/troubleshooting-importerror.html
+
+Please note and check the following:
+
+ * The Python version is: Python%d.%d from "%s"
+ * The NumPy version is: "%s"
+
+and make sure that they are the versions you expect.
+Please carefully study the documentation linked above for further help.
+
+Original error was: %s
+""" % (sys.version_info[0], sys.version_info[1], sys.executable,
+ __version__, exc)
+ raise ImportError(msg)
+finally:
+ for envkey in env_added:
+ del os.environ[envkey]
+del envkey
+del env_added
+del os
+
+from . import umath
+
+# Check that multiarray,umath are pure python modules wrapping
+# _multiarray_umath and not either of the old c-extension modules
+if not (hasattr(multiarray, '_multiarray_umath') and
+ hasattr(umath, '_multiarray_umath')):
+ import sys
+ path = sys.modules['numpy'].__path__
+ msg = ("Something is wrong with the numpy installation. "
+ "While importing we detected an older version of "
+ "numpy in {}. One method of fixing this is to repeatedly uninstall "
+ "numpy until none is found, then reinstall this version.")
+ raise ImportError(msg.format(path))
+
+from . import numerictypes as nt
+from .numerictypes import sctypes, sctypeDict
+multiarray.set_typeDict(nt.sctypeDict)
+from . import numeric
+from .numeric import *
+from . import fromnumeric
+from .fromnumeric import *
+from .records import record, recarray
+# Note: module name memmap is overwritten by a class with same name
+from .memmap import *
+from . import function_base
+from .function_base import *
+from . import _machar
+from . import getlimits
+from .getlimits import *
+from . import shape_base
+from .shape_base import *
+from . import einsumfunc
+from .einsumfunc import *
+del nt
+
+from .numeric import absolute as abs
+
+# do this after everything else, to minimize the chance of this misleadingly
+# appearing in an import-time traceback
+from . import _add_newdocs
+from . import _add_newdocs_scalars
+# add these for module-freeze analysis (like PyInstaller)
+from . import _dtype_ctypes
+from . import _internal
+from . import _dtype
+from . import _methods
+
+acos = numeric.arccos
+acosh = numeric.arccosh
+asin = numeric.arcsin
+asinh = numeric.arcsinh
+atan = numeric.arctan
+atanh = numeric.arctanh
+atan2 = numeric.arctan2
+concat = numeric.concatenate
+bitwise_left_shift = numeric.left_shift
+bitwise_invert = numeric.invert
+bitwise_right_shift = numeric.right_shift
+permute_dims = numeric.transpose
+pow = numeric.power
+
+__all__ = [
+ "abs", "acos", "acosh", "asin", "asinh", "atan", "atanh", "atan2",
+ "bitwise_invert", "bitwise_left_shift", "bitwise_right_shift", "concat",
+ "pow", "permute_dims", "memmap", "sctypeDict", "record", "recarray"
+]
+__all__ += numeric.__all__
+__all__ += function_base.__all__
+__all__ += getlimits.__all__
+__all__ += shape_base.__all__
+__all__ += einsumfunc.__all__
+
+
+def _ufunc_reduce(func):
+ # Report the `__name__`. pickle will try to find the module. Note that
+ # pickle supports for this `__name__` to be a `__qualname__`. It may
+ # make sense to add a `__qualname__` to ufuncs, to allow this more
+ # explicitly (Numba has ufuncs as attributes).
+ # See also: https://github.com/dask/distributed/issues/3450
+ return func.__name__
+
+
+def _DType_reconstruct(scalar_type):
+ # This is a work-around to pickle type(np.dtype(np.float64)), etc.
+ # and it should eventually be replaced with a better solution, e.g. when
+ # DTypes become HeapTypes.
+ return type(dtype(scalar_type))
+
+
+def _DType_reduce(DType):
+ # As types/classes, most DTypes can simply be pickled by their name:
+ if not DType._legacy or DType.__module__ == "numpy.dtypes":
+ return DType.__name__
+
+ # However, user defined legacy dtypes (like rational) do not end up in
+ # `numpy.dtypes` as module and do not have a public class at all.
+ # For these, we pickle them by reconstructing them from the scalar type:
+ scalar_type = DType.type
+ return _DType_reconstruct, (scalar_type,)
+
+
+def __getattr__(name):
+ # Deprecated 2022-11-22, NumPy 1.25.
+ if name == "MachAr":
+ import warnings
+ warnings.warn(
+ "The `np._core.MachAr` is considered private API (NumPy 1.24)",
+ DeprecationWarning, stacklevel=2,
+ )
+ return _machar.MachAr
+ raise AttributeError(f"Module {__name__!r} has no attribute {name!r}")
+
+
+import copyreg
+
+copyreg.pickle(ufunc, _ufunc_reduce)
+copyreg.pickle(type(dtype), _DType_reduce, _DType_reconstruct)
+
+# Unclutter namespace (must keep _*_reconstruct for unpickling)
+del copyreg, _ufunc_reduce, _DType_reduce
+
+from numpy._pytesttester import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__init__.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__init__.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..40d9c411b97cf7f9e5df910b7567db9238a61e5d
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__init__.pyi
@@ -0,0 +1,2 @@
+# NOTE: The `np._core` namespace is deliberately kept empty due to it
+# being private
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d0b6bcc68eaaad0634300755c2ddea7665b09f46
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/_add_newdocs_scalars.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/_add_newdocs_scalars.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e1cfd92a7fd363e063a90f63ec669a6178cde45f
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/_add_newdocs_scalars.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/_asarray.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/_asarray.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..15e854dcec6dea6260dd824454dd1208a81dde57
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/_asarray.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/_dtype.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/_dtype.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..38bc07bf3b989aa9b4edea1e81a85197479f1018
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/_dtype.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/_dtype_ctypes.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/_dtype_ctypes.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..50e699a74e686b2aa44bf77b63041c27cc7172ab
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/_dtype_ctypes.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/_exceptions.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/_exceptions.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..56a59c422934256dfcca0f62c30336ff0c2c6552
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/_exceptions.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/_internal.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/_internal.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..05de8f441819d74f2830e80845dd44e4b84a7493
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/_internal.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/_machar.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/_machar.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..37e29782473d4ca6ce8820e1475af6a8a971cd32
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/_machar.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/_methods.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/_methods.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6d128630c526ac3aaecc2d8e50b33fc09334ec38
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/_methods.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/_string_helpers.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/_string_helpers.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dde56a63439db22775c6d279f7b8e6998603a07c
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/_string_helpers.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/_type_aliases.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/_type_aliases.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a8c7b115938fbe3f9ab9fdac66bb82817b0b10d0
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/_type_aliases.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/_ufunc_config.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/_ufunc_config.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0a01358a4a13405dc71468d9ff0c887f17a24773
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/_ufunc_config.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/arrayprint.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/arrayprint.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..efbe31eb96841c7fe3d5c096cff60a49a4d23c19
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/arrayprint.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/defchararray.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/defchararray.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a9fffa8b68203f7593a7a6f10c10ac4465a8ce07
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/defchararray.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/einsumfunc.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/einsumfunc.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8f9d2b4a8de2c6c0e11ea59afdbb980dc59c27b8
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/einsumfunc.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/function_base.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/function_base.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b66d3f0b6321440b36b623145ef0a22b977f5f91
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/function_base.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/getlimits.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/getlimits.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e6791116a3567e599fe16974a71d0253a689d6e2
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/getlimits.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/memmap.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/memmap.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f18409ad597c1d4daa40445b2d596dd40daaf8d0
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/memmap.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/multiarray.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/multiarray.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3423d5729f6518cfdef53ecf170e515979ad19f3
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/multiarray.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/numeric.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/numeric.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..33803e09f65e8c62f262b1a5301be8bc8ee153cd
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/numeric.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/numerictypes.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/numerictypes.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7679a0b4cfa8c58cf635ba001980bec001b0e545
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/numerictypes.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/overrides.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/overrides.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..336f2a44b46bcebbd365de189ad288e8eb54a2a5
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/overrides.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/printoptions.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/printoptions.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3d2f023dad2379ce4ade12b272e9c5857432a8a4
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/printoptions.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/records.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/records.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f91f0e33387ca1b1963ace5195e9cf2f89570663
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/records.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/shape_base.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/shape_base.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..133101517ee4f7ec609b479e6b73d2332b3b7cfd
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/shape_base.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/strings.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/strings.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..20e63110df9a75fe1c82817db51afd8ae2fece9f
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/strings.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/umath.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/umath.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..410e79a0d0b19c77a57bde038118c0136c70ad53
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/__pycache__/umath.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_add_newdocs.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_add_newdocs.py
new file mode 100644
index 0000000000000000000000000000000000000000..d860aadedd83f3bcfcb3afef3fe194ec99730517
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_add_newdocs.py
@@ -0,0 +1,6974 @@
+"""
+This is only meant to add docs to objects defined in C-extension modules.
+The purpose is to allow easier editing of the docstrings without
+requiring a re-compile.
+
+NOTE: Many of the methods of ndarray have corresponding functions.
+ If you update these docstrings, please keep also the ones in
+ _core/fromnumeric.py, matrixlib/defmatrix.py up-to-date.
+
+"""
+
+from numpy._core.function_base import add_newdoc
+from numpy._core.overrides import get_array_function_like_doc
+
+
+###############################################################################
+#
+# flatiter
+#
+# flatiter needs a toplevel description
+#
+###############################################################################
+
+add_newdoc('numpy._core', 'flatiter',
+ """
+ Flat iterator object to iterate over arrays.
+
+ A `flatiter` iterator is returned by ``x.flat`` for any array `x`.
+ It allows iterating over the array as if it were a 1-D array,
+ either in a for-loop or by calling its `next` method.
+
+ Iteration is done in row-major, C-style order (the last
+ index varying the fastest). The iterator can also be indexed using
+ basic slicing or advanced indexing.
+
+ See Also
+ --------
+ ndarray.flat : Return a flat iterator over an array.
+ ndarray.flatten : Returns a flattened copy of an array.
+
+ Notes
+ -----
+ A `flatiter` iterator can not be constructed directly from Python code
+ by calling the `flatiter` constructor.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.arange(6).reshape(2, 3)
+ >>> fl = x.flat
+ >>> type(fl)
+
+ >>> for item in fl:
+ ... print(item)
+ ...
+ 0
+ 1
+ 2
+ 3
+ 4
+ 5
+
+ >>> fl[2:4]
+ array([2, 3])
+
+ """)
+
+# flatiter attributes
+
+add_newdoc('numpy._core', 'flatiter', ('base',
+ """
+ A reference to the array that is iterated over.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.arange(5)
+ >>> fl = x.flat
+ >>> fl.base is x
+ True
+
+ """))
+
+
+add_newdoc('numpy._core', 'flatiter', ('coords',
+ """
+ An N-dimensional tuple of current coordinates.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.arange(6).reshape(2, 3)
+ >>> fl = x.flat
+ >>> fl.coords
+ (0, 0)
+ >>> next(fl)
+ 0
+ >>> fl.coords
+ (0, 1)
+
+ """))
+
+
+add_newdoc('numpy._core', 'flatiter', ('index',
+ """
+ Current flat index into the array.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.arange(6).reshape(2, 3)
+ >>> fl = x.flat
+ >>> fl.index
+ 0
+ >>> next(fl)
+ 0
+ >>> fl.index
+ 1
+
+ """))
+
+# flatiter functions
+
+add_newdoc('numpy._core', 'flatiter', ('__array__',
+ """__array__(type=None) Get array from iterator
+
+ """))
+
+
+add_newdoc('numpy._core', 'flatiter', ('copy',
+ """
+ copy()
+
+ Get a copy of the iterator as a 1-D array.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.arange(6).reshape(2, 3)
+ >>> x
+ array([[0, 1, 2],
+ [3, 4, 5]])
+ >>> fl = x.flat
+ >>> fl.copy()
+ array([0, 1, 2, 3, 4, 5])
+
+ """))
+
+
+###############################################################################
+#
+# nditer
+#
+###############################################################################
+
+add_newdoc('numpy._core', 'nditer',
+ """
+ nditer(op, flags=None, op_flags=None, op_dtypes=None, order='K',
+ casting='safe', op_axes=None, itershape=None, buffersize=0)
+
+ Efficient multi-dimensional iterator object to iterate over arrays.
+ To get started using this object, see the
+ :ref:`introductory guide to array iteration `.
+
+ Parameters
+ ----------
+ op : ndarray or sequence of array_like
+ The array(s) to iterate over.
+
+ flags : sequence of str, optional
+ Flags to control the behavior of the iterator.
+
+ * ``buffered`` enables buffering when required.
+ * ``c_index`` causes a C-order index to be tracked.
+ * ``f_index`` causes a Fortran-order index to be tracked.
+ * ``multi_index`` causes a multi-index, or a tuple of indices
+ with one per iteration dimension, to be tracked.
+ * ``common_dtype`` causes all the operands to be converted to
+ a common data type, with copying or buffering as necessary.
+ * ``copy_if_overlap`` causes the iterator to determine if read
+ operands have overlap with write operands, and make temporary
+ copies as necessary to avoid overlap. False positives (needless
+ copying) are possible in some cases.
+ * ``delay_bufalloc`` delays allocation of the buffers until
+ a reset() call is made. Allows ``allocate`` operands to
+ be initialized before their values are copied into the buffers.
+ * ``external_loop`` causes the ``values`` given to be
+ one-dimensional arrays with multiple values instead of
+ zero-dimensional arrays.
+ * ``grow_inner`` allows the ``value`` array sizes to be made
+ larger than the buffer size when both ``buffered`` and
+ ``external_loop`` is used.
+ * ``ranged`` allows the iterator to be restricted to a sub-range
+ of the iterindex values.
+ * ``refs_ok`` enables iteration of reference types, such as
+ object arrays.
+ * ``reduce_ok`` enables iteration of ``readwrite`` operands
+ which are broadcasted, also known as reduction operands.
+ * ``zerosize_ok`` allows `itersize` to be zero.
+ op_flags : list of list of str, optional
+ This is a list of flags for each operand. At minimum, one of
+ ``readonly``, ``readwrite``, or ``writeonly`` must be specified.
+
+ * ``readonly`` indicates the operand will only be read from.
+ * ``readwrite`` indicates the operand will be read from and written to.
+ * ``writeonly`` indicates the operand will only be written to.
+ * ``no_broadcast`` prevents the operand from being broadcasted.
+ * ``contig`` forces the operand data to be contiguous.
+ * ``aligned`` forces the operand data to be aligned.
+ * ``nbo`` forces the operand data to be in native byte order.
+ * ``copy`` allows a temporary read-only copy if required.
+ * ``updateifcopy`` allows a temporary read-write copy if required.
+ * ``allocate`` causes the array to be allocated if it is None
+ in the ``op`` parameter.
+ * ``no_subtype`` prevents an ``allocate`` operand from using a subtype.
+ * ``arraymask`` indicates that this operand is the mask to use
+ for selecting elements when writing to operands with the
+ 'writemasked' flag set. The iterator does not enforce this,
+ but when writing from a buffer back to the array, it only
+ copies those elements indicated by this mask.
+ * ``writemasked`` indicates that only elements where the chosen
+ ``arraymask`` operand is True will be written to.
+ * ``overlap_assume_elementwise`` can be used to mark operands that are
+ accessed only in the iterator order, to allow less conservative
+ copying when ``copy_if_overlap`` is present.
+ op_dtypes : dtype or tuple of dtype(s), optional
+ The required data type(s) of the operands. If copying or buffering
+ is enabled, the data will be converted to/from their original types.
+ order : {'C', 'F', 'A', 'K'}, optional
+ Controls the iteration order. 'C' means C order, 'F' means
+ Fortran order, 'A' means 'F' order if all the arrays are Fortran
+ contiguous, 'C' order otherwise, and 'K' means as close to the
+ order the array elements appear in memory as possible. This also
+ affects the element memory order of ``allocate`` operands, as they
+ are allocated to be compatible with iteration order.
+ Default is 'K'.
+ casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
+ Controls what kind of data casting may occur when making a copy
+ or buffering. Setting this to 'unsafe' is not recommended,
+ as it can adversely affect accumulations.
+
+ * 'no' means the data types should not be cast at all.
+ * 'equiv' means only byte-order changes are allowed.
+ * 'safe' means only casts which can preserve values are allowed.
+ * 'same_kind' means only safe casts or casts within a kind,
+ like float64 to float32, are allowed.
+ * 'unsafe' means any data conversions may be done.
+ op_axes : list of list of ints, optional
+ If provided, is a list of ints or None for each operands.
+ The list of axes for an operand is a mapping from the dimensions
+ of the iterator to the dimensions of the operand. A value of
+ -1 can be placed for entries, causing that dimension to be
+ treated as `newaxis`.
+ itershape : tuple of ints, optional
+ The desired shape of the iterator. This allows ``allocate`` operands
+ with a dimension mapped by op_axes not corresponding to a dimension
+ of a different operand to get a value not equal to 1 for that
+ dimension.
+ buffersize : int, optional
+ When buffering is enabled, controls the size of the temporary
+ buffers. Set to 0 for the default value.
+
+ Attributes
+ ----------
+ dtypes : tuple of dtype(s)
+ The data types of the values provided in `value`. This may be
+ different from the operand data types if buffering is enabled.
+ Valid only before the iterator is closed.
+ finished : bool
+ Whether the iteration over the operands is finished or not.
+ has_delayed_bufalloc : bool
+ If True, the iterator was created with the ``delay_bufalloc`` flag,
+ and no reset() function was called on it yet.
+ has_index : bool
+ If True, the iterator was created with either the ``c_index`` or
+ the ``f_index`` flag, and the property `index` can be used to
+ retrieve it.
+ has_multi_index : bool
+ If True, the iterator was created with the ``multi_index`` flag,
+ and the property `multi_index` can be used to retrieve it.
+ index
+ When the ``c_index`` or ``f_index`` flag was used, this property
+ provides access to the index. Raises a ValueError if accessed
+ and ``has_index`` is False.
+ iterationneedsapi : bool
+ Whether iteration requires access to the Python API, for example
+ if one of the operands is an object array.
+ iterindex : int
+ An index which matches the order of iteration.
+ itersize : int
+ Size of the iterator.
+ itviews
+ Structured view(s) of `operands` in memory, matching the reordered
+ and optimized iterator access pattern. Valid only before the iterator
+ is closed.
+ multi_index
+ When the ``multi_index`` flag was used, this property
+ provides access to the index. Raises a ValueError if accessed
+ accessed and ``has_multi_index`` is False.
+ ndim : int
+ The dimensions of the iterator.
+ nop : int
+ The number of iterator operands.
+ operands : tuple of operand(s)
+ The array(s) to be iterated over. Valid only before the iterator is
+ closed.
+ shape : tuple of ints
+ Shape tuple, the shape of the iterator.
+ value
+ Value of ``operands`` at current iteration. Normally, this is a
+ tuple of array scalars, but if the flag ``external_loop`` is used,
+ it is a tuple of one dimensional arrays.
+
+ Notes
+ -----
+ `nditer` supersedes `flatiter`. The iterator implementation behind
+ `nditer` is also exposed by the NumPy C API.
+
+ The Python exposure supplies two iteration interfaces, one which follows
+ the Python iterator protocol, and another which mirrors the C-style
+ do-while pattern. The native Python approach is better in most cases, but
+ if you need the coordinates or index of an iterator, use the C-style pattern.
+
+ Examples
+ --------
+ Here is how we might write an ``iter_add`` function, using the
+ Python iterator protocol:
+
+ >>> import numpy as np
+
+ >>> def iter_add_py(x, y, out=None):
+ ... addop = np.add
+ ... it = np.nditer([x, y, out], [],
+ ... [['readonly'], ['readonly'], ['writeonly','allocate']])
+ ... with it:
+ ... for (a, b, c) in it:
+ ... addop(a, b, out=c)
+ ... return it.operands[2]
+
+ Here is the same function, but following the C-style pattern:
+
+ >>> def iter_add(x, y, out=None):
+ ... addop = np.add
+ ... it = np.nditer([x, y, out], [],
+ ... [['readonly'], ['readonly'], ['writeonly','allocate']])
+ ... with it:
+ ... while not it.finished:
+ ... addop(it[0], it[1], out=it[2])
+ ... it.iternext()
+ ... return it.operands[2]
+
+ Here is an example outer product function:
+
+ >>> def outer_it(x, y, out=None):
+ ... mulop = np.multiply
+ ... it = np.nditer([x, y, out], ['external_loop'],
+ ... [['readonly'], ['readonly'], ['writeonly', 'allocate']],
+ ... op_axes=[list(range(x.ndim)) + [-1] * y.ndim,
+ ... [-1] * x.ndim + list(range(y.ndim)),
+ ... None])
+ ... with it:
+ ... for (a, b, c) in it:
+ ... mulop(a, b, out=c)
+ ... return it.operands[2]
+
+ >>> a = np.arange(2)+1
+ >>> b = np.arange(3)+1
+ >>> outer_it(a,b)
+ array([[1, 2, 3],
+ [2, 4, 6]])
+
+ Here is an example function which operates like a "lambda" ufunc:
+
+ >>> def luf(lamdaexpr, *args, **kwargs):
+ ... '''luf(lambdaexpr, op1, ..., opn, out=None, order='K', casting='safe', buffersize=0)'''
+ ... nargs = len(args)
+ ... op = (kwargs.get('out',None),) + args
+ ... it = np.nditer(op, ['buffered','external_loop'],
+ ... [['writeonly','allocate','no_broadcast']] +
+ ... [['readonly','nbo','aligned']]*nargs,
+ ... order=kwargs.get('order','K'),
+ ... casting=kwargs.get('casting','safe'),
+ ... buffersize=kwargs.get('buffersize',0))
+ ... while not it.finished:
+ ... it[0] = lamdaexpr(*it[1:])
+ ... it.iternext()
+ ... return it.operands[0]
+
+ >>> a = np.arange(5)
+ >>> b = np.ones(5)
+ >>> luf(lambda i,j:i*i + j/2, a, b)
+ array([ 0.5, 1.5, 4.5, 9.5, 16.5])
+
+ If operand flags ``"writeonly"`` or ``"readwrite"`` are used the
+ operands may be views into the original data with the
+ `WRITEBACKIFCOPY` flag. In this case `nditer` must be used as a
+ context manager or the `nditer.close` method must be called before
+ using the result. The temporary data will be written back to the
+ original data when the :meth:`~object.__exit__` function is called
+ but not before:
+
+ >>> a = np.arange(6, dtype='i4')[::-2]
+ >>> with np.nditer(a, [],
+ ... [['writeonly', 'updateifcopy']],
+ ... casting='unsafe',
+ ... op_dtypes=[np.dtype('f4')]) as i:
+ ... x = i.operands[0]
+ ... x[:] = [-1, -2, -3]
+ ... # a still unchanged here
+ >>> a, x
+ (array([-1, -2, -3], dtype=int32), array([-1., -2., -3.], dtype=float32))
+
+ It is important to note that once the iterator is exited, dangling
+ references (like `x` in the example) may or may not share data with
+ the original data `a`. If writeback semantics were active, i.e. if
+ `x.base.flags.writebackifcopy` is `True`, then exiting the iterator
+ will sever the connection between `x` and `a`, writing to `x` will
+ no longer write to `a`. If writeback semantics are not active, then
+ `x.data` will still point at some part of `a.data`, and writing to
+ one will affect the other.
+
+ Context management and the `close` method appeared in version 1.15.0.
+
+ """)
+
+# nditer methods
+
+add_newdoc('numpy._core', 'nditer', ('copy',
+ """
+ copy()
+
+ Get a copy of the iterator in its current state.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.arange(10)
+ >>> y = x + 1
+ >>> it = np.nditer([x, y])
+ >>> next(it)
+ (array(0), array(1))
+ >>> it2 = it.copy()
+ >>> next(it2)
+ (array(1), array(2))
+
+ """))
+
+add_newdoc('numpy._core', 'nditer', ('operands',
+ """
+ operands[`Slice`]
+
+ The array(s) to be iterated over. Valid only before the iterator is closed.
+ """))
+
+add_newdoc('numpy._core', 'nditer', ('debug_print',
+ """
+ debug_print()
+
+ Print the current state of the `nditer` instance and debug info to stdout.
+
+ """))
+
+add_newdoc('numpy._core', 'nditer', ('enable_external_loop',
+ """
+ enable_external_loop()
+
+ When the "external_loop" was not used during construction, but
+ is desired, this modifies the iterator to behave as if the flag
+ was specified.
+
+ """))
+
+add_newdoc('numpy._core', 'nditer', ('iternext',
+ """
+ iternext()
+
+ Check whether iterations are left, and perform a single internal iteration
+ without returning the result. Used in the C-style pattern do-while
+ pattern. For an example, see `nditer`.
+
+ Returns
+ -------
+ iternext : bool
+ Whether or not there are iterations left.
+
+ """))
+
+add_newdoc('numpy._core', 'nditer', ('remove_axis',
+ """
+ remove_axis(i, /)
+
+ Removes axis `i` from the iterator. Requires that the flag "multi_index"
+ be enabled.
+
+ """))
+
+add_newdoc('numpy._core', 'nditer', ('remove_multi_index',
+ """
+ remove_multi_index()
+
+ When the "multi_index" flag was specified, this removes it, allowing
+ the internal iteration structure to be optimized further.
+
+ """))
+
+add_newdoc('numpy._core', 'nditer', ('reset',
+ """
+ reset()
+
+ Reset the iterator to its initial state.
+
+ """))
+
+add_newdoc('numpy._core', 'nested_iters',
+ """
+ nested_iters(op, axes, flags=None, op_flags=None, op_dtypes=None, \
+ order="K", casting="safe", buffersize=0)
+
+ Create nditers for use in nested loops
+
+ Create a tuple of `nditer` objects which iterate in nested loops over
+ different axes of the op argument. The first iterator is used in the
+ outermost loop, the last in the innermost loop. Advancing one will change
+ the subsequent iterators to point at its new element.
+
+ Parameters
+ ----------
+ op : ndarray or sequence of array_like
+ The array(s) to iterate over.
+
+ axes : list of list of int
+ Each item is used as an "op_axes" argument to an nditer
+
+ flags, op_flags, op_dtypes, order, casting, buffersize (optional)
+ See `nditer` parameters of the same name
+
+ Returns
+ -------
+ iters : tuple of nditer
+ An nditer for each item in `axes`, outermost first
+
+ See Also
+ --------
+ nditer
+
+ Examples
+ --------
+
+ Basic usage. Note how y is the "flattened" version of
+ [a[:, 0, :], a[:, 1, 0], a[:, 2, :]] since we specified
+ the first iter's axes as [1]
+
+ >>> import numpy as np
+ >>> a = np.arange(12).reshape(2, 3, 2)
+ >>> i, j = np.nested_iters(a, [[1], [0, 2]], flags=["multi_index"])
+ >>> for x in i:
+ ... print(i.multi_index)
+ ... for y in j:
+ ... print('', j.multi_index, y)
+ (0,)
+ (0, 0) 0
+ (0, 1) 1
+ (1, 0) 6
+ (1, 1) 7
+ (1,)
+ (0, 0) 2
+ (0, 1) 3
+ (1, 0) 8
+ (1, 1) 9
+ (2,)
+ (0, 0) 4
+ (0, 1) 5
+ (1, 0) 10
+ (1, 1) 11
+
+ """)
+
+add_newdoc('numpy._core', 'nditer', ('close',
+ """
+ close()
+
+ Resolve all writeback semantics in writeable operands.
+
+ See Also
+ --------
+
+ :ref:`nditer-context-manager`
+
+ """))
+
+
+###############################################################################
+#
+# broadcast
+#
+###############################################################################
+
+add_newdoc('numpy._core', 'broadcast',
+ """
+ Produce an object that mimics broadcasting.
+
+ Parameters
+ ----------
+ in1, in2, ... : array_like
+ Input parameters.
+
+ Returns
+ -------
+ b : broadcast object
+ Broadcast the input parameters against one another, and
+ return an object that encapsulates the result.
+ Amongst others, it has ``shape`` and ``nd`` properties, and
+ may be used as an iterator.
+
+ See Also
+ --------
+ broadcast_arrays
+ broadcast_to
+ broadcast_shapes
+
+ Examples
+ --------
+
+ Manually adding two vectors, using broadcasting:
+
+ >>> import numpy as np
+ >>> x = np.array([[1], [2], [3]])
+ >>> y = np.array([4, 5, 6])
+ >>> b = np.broadcast(x, y)
+
+ >>> out = np.empty(b.shape)
+ >>> out.flat = [u+v for (u,v) in b]
+ >>> out
+ array([[5., 6., 7.],
+ [6., 7., 8.],
+ [7., 8., 9.]])
+
+ Compare against built-in broadcasting:
+
+ >>> x + y
+ array([[5, 6, 7],
+ [6, 7, 8],
+ [7, 8, 9]])
+
+ """)
+
+# attributes
+
+add_newdoc('numpy._core', 'broadcast', ('index',
+ """
+ current index in broadcasted result
+
+ Examples
+ --------
+
+ >>> import numpy as np
+ >>> x = np.array([[1], [2], [3]])
+ >>> y = np.array([4, 5, 6])
+ >>> b = np.broadcast(x, y)
+ >>> b.index
+ 0
+ >>> next(b), next(b), next(b)
+ ((1, 4), (1, 5), (1, 6))
+ >>> b.index
+ 3
+
+ """))
+
+add_newdoc('numpy._core', 'broadcast', ('iters',
+ """
+ tuple of iterators along ``self``'s "components."
+
+ Returns a tuple of `numpy.flatiter` objects, one for each "component"
+ of ``self``.
+
+ See Also
+ --------
+ numpy.flatiter
+
+ Examples
+ --------
+
+ >>> import numpy as np
+ >>> x = np.array([1, 2, 3])
+ >>> y = np.array([[4], [5], [6]])
+ >>> b = np.broadcast(x, y)
+ >>> row, col = b.iters
+ >>> next(row), next(col)
+ (1, 4)
+
+ """))
+
+add_newdoc('numpy._core', 'broadcast', ('ndim',
+ """
+ Number of dimensions of broadcasted result. Alias for `nd`.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.array([1, 2, 3])
+ >>> y = np.array([[4], [5], [6]])
+ >>> b = np.broadcast(x, y)
+ >>> b.ndim
+ 2
+
+ """))
+
+add_newdoc('numpy._core', 'broadcast', ('nd',
+ """
+ Number of dimensions of broadcasted result. For code intended for NumPy
+ 1.12.0 and later the more consistent `ndim` is preferred.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.array([1, 2, 3])
+ >>> y = np.array([[4], [5], [6]])
+ >>> b = np.broadcast(x, y)
+ >>> b.nd
+ 2
+
+ """))
+
+add_newdoc('numpy._core', 'broadcast', ('numiter',
+ """
+ Number of iterators possessed by the broadcasted result.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.array([1, 2, 3])
+ >>> y = np.array([[4], [5], [6]])
+ >>> b = np.broadcast(x, y)
+ >>> b.numiter
+ 2
+
+ """))
+
+add_newdoc('numpy._core', 'broadcast', ('shape',
+ """
+ Shape of broadcasted result.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.array([1, 2, 3])
+ >>> y = np.array([[4], [5], [6]])
+ >>> b = np.broadcast(x, y)
+ >>> b.shape
+ (3, 3)
+
+ """))
+
+add_newdoc('numpy._core', 'broadcast', ('size',
+ """
+ Total size of broadcasted result.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.array([1, 2, 3])
+ >>> y = np.array([[4], [5], [6]])
+ >>> b = np.broadcast(x, y)
+ >>> b.size
+ 9
+
+ """))
+
+add_newdoc('numpy._core', 'broadcast', ('reset',
+ """
+ reset()
+
+ Reset the broadcasted result's iterator(s).
+
+ Parameters
+ ----------
+ None
+
+ Returns
+ -------
+ None
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.array([1, 2, 3])
+ >>> y = np.array([[4], [5], [6]])
+ >>> b = np.broadcast(x, y)
+ >>> b.index
+ 0
+ >>> next(b), next(b), next(b)
+ ((1, 4), (2, 4), (3, 4))
+ >>> b.index
+ 3
+ >>> b.reset()
+ >>> b.index
+ 0
+
+ """))
+
+###############################################################################
+#
+# numpy functions
+#
+###############################################################################
+
+add_newdoc('numpy._core.multiarray', 'array',
+ """
+ array(object, dtype=None, *, copy=True, order='K', subok=False, ndmin=0,
+ like=None)
+
+ Create an array.
+
+ Parameters
+ ----------
+ object : array_like
+ An array, any object exposing the array interface, an object whose
+ ``__array__`` method returns an array, or any (nested) sequence.
+ If object is a scalar, a 0-dimensional array containing object is
+ returned.
+ dtype : data-type, optional
+ The desired data-type for the array. If not given, NumPy will try to use
+ a default ``dtype`` that can represent the values (by applying promotion
+ rules when necessary.)
+ copy : bool, optional
+ If ``True`` (default), then the array data is copied. If ``None``,
+ a copy will only be made if ``__array__`` returns a copy, if obj is
+ a nested sequence, or if a copy is needed to satisfy any of the other
+ requirements (``dtype``, ``order``, etc.). Note that any copy of
+ the data is shallow, i.e., for arrays with object dtype, the new
+ array will point to the same objects. See Examples for `ndarray.copy`.
+ For ``False`` it raises a ``ValueError`` if a copy cannot be avoided.
+ Default: ``True``.
+ order : {'K', 'A', 'C', 'F'}, optional
+ Specify the memory layout of the array. If object is not an array, the
+ newly created array will be in C order (row major) unless 'F' is
+ specified, in which case it will be in Fortran order (column major).
+ If object is an array the following holds.
+
+ ===== ========= ===================================================
+ order no copy copy=True
+ ===== ========= ===================================================
+ 'K' unchanged F & C order preserved, otherwise most similar order
+ 'A' unchanged F order if input is F and not C, otherwise C order
+ 'C' C order C order
+ 'F' F order F order
+ ===== ========= ===================================================
+
+ When ``copy=None`` and a copy is made for other reasons, the result is
+ the same as if ``copy=True``, with some exceptions for 'A', see the
+ Notes section. The default order is 'K'.
+ subok : bool, optional
+ If True, then sub-classes will be passed-through, otherwise
+ the returned array will be forced to be a base-class array (default).
+ ndmin : int, optional
+ Specifies the minimum number of dimensions that the resulting
+ array should have. Ones will be prepended to the shape as
+ needed to meet this requirement.
+ ${ARRAY_FUNCTION_LIKE}
+
+ .. versionadded:: 1.20.0
+
+ Returns
+ -------
+ out : ndarray
+ An array object satisfying the specified requirements.
+
+ See Also
+ --------
+ empty_like : Return an empty array with shape and type of input.
+ ones_like : Return an array of ones with shape and type of input.
+ zeros_like : Return an array of zeros with shape and type of input.
+ full_like : Return a new array with shape of input filled with value.
+ empty : Return a new uninitialized array.
+ ones : Return a new array setting values to one.
+ zeros : Return a new array setting values to zero.
+ full : Return a new array of given shape filled with value.
+ copy: Return an array copy of the given object.
+
+
+ Notes
+ -----
+ When order is 'A' and ``object`` is an array in neither 'C' nor 'F' order,
+ and a copy is forced by a change in dtype, then the order of the result is
+ not necessarily 'C' as expected. This is likely a bug.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.array([1, 2, 3])
+ array([1, 2, 3])
+
+ Upcasting:
+
+ >>> np.array([1, 2, 3.0])
+ array([ 1., 2., 3.])
+
+ More than one dimension:
+
+ >>> np.array([[1, 2], [3, 4]])
+ array([[1, 2],
+ [3, 4]])
+
+ Minimum dimensions 2:
+
+ >>> np.array([1, 2, 3], ndmin=2)
+ array([[1, 2, 3]])
+
+ Type provided:
+
+ >>> np.array([1, 2, 3], dtype=complex)
+ array([ 1.+0.j, 2.+0.j, 3.+0.j])
+
+ Data-type consisting of more than one element:
+
+ >>> x = np.array([(1,2),(3,4)],dtype=[('a','>> x['a']
+ array([1, 3], dtype=int32)
+
+ Creating an array from sub-classes:
+
+ >>> np.array(np.asmatrix('1 2; 3 4'))
+ array([[1, 2],
+ [3, 4]])
+
+ >>> np.array(np.asmatrix('1 2; 3 4'), subok=True)
+ matrix([[1, 2],
+ [3, 4]])
+
+ """)
+
+add_newdoc('numpy._core.multiarray', 'asarray',
+ """
+ asarray(a, dtype=None, order=None, *, device=None, copy=None, like=None)
+
+ Convert the input to an array.
+
+ Parameters
+ ----------
+ a : array_like
+ Input data, in any form that can be converted to an array. This
+ includes lists, lists of tuples, tuples, tuples of tuples, tuples
+ of lists and ndarrays.
+ dtype : data-type, optional
+ By default, the data-type is inferred from the input data.
+ order : {'C', 'F', 'A', 'K'}, optional
+ Memory layout. 'A' and 'K' depend on the order of input array a.
+ 'C' row-major (C-style),
+ 'F' column-major (Fortran-style) memory representation.
+ 'A' (any) means 'F' if `a` is Fortran contiguous, 'C' otherwise
+ 'K' (keep) preserve input order
+ Defaults to 'K'.
+ device : str, optional
+ The device on which to place the created array. Default: ``None``.
+ For Array-API interoperability only, so must be ``"cpu"`` if passed.
+
+ .. versionadded:: 2.0.0
+ copy : bool, optional
+ If ``True``, then the object is copied. If ``None`` then the object is
+ copied only if needed, i.e. if ``__array__`` returns a copy, if obj
+ is a nested sequence, or if a copy is needed to satisfy any of
+ the other requirements (``dtype``, ``order``, etc.).
+ For ``False`` it raises a ``ValueError`` if a copy cannot be avoided.
+ Default: ``None``.
+
+ .. versionadded:: 2.0.0
+ ${ARRAY_FUNCTION_LIKE}
+
+ .. versionadded:: 1.20.0
+
+ Returns
+ -------
+ out : ndarray
+ Array interpretation of ``a``. No copy is performed if the input
+ is already an ndarray with matching dtype and order. If ``a`` is a
+ subclass of ndarray, a base class ndarray is returned.
+
+ See Also
+ --------
+ asanyarray : Similar function which passes through subclasses.
+ ascontiguousarray : Convert input to a contiguous array.
+ asfortranarray : Convert input to an ndarray with column-major
+ memory order.
+ asarray_chkfinite : Similar function which checks input for NaNs and Infs.
+ fromiter : Create an array from an iterator.
+ fromfunction : Construct an array by executing a function on grid
+ positions.
+
+ Examples
+ --------
+ Convert a list into an array:
+
+ >>> a = [1, 2]
+ >>> import numpy as np
+ >>> np.asarray(a)
+ array([1, 2])
+
+ Existing arrays are not copied:
+
+ >>> a = np.array([1, 2])
+ >>> np.asarray(a) is a
+ True
+
+ If `dtype` is set, array is copied only if dtype does not match:
+
+ >>> a = np.array([1, 2], dtype=np.float32)
+ >>> np.shares_memory(np.asarray(a, dtype=np.float32), a)
+ True
+ >>> np.shares_memory(np.asarray(a, dtype=np.float64), a)
+ False
+
+ Contrary to `asanyarray`, ndarray subclasses are not passed through:
+
+ >>> issubclass(np.recarray, np.ndarray)
+ True
+ >>> a = np.array([(1., 2), (3., 4)], dtype='f4,i4').view(np.recarray)
+ >>> np.asarray(a) is a
+ False
+ >>> np.asanyarray(a) is a
+ True
+
+ """)
+
+add_newdoc('numpy._core.multiarray', 'asanyarray',
+ """
+ asanyarray(a, dtype=None, order=None, *, device=None, copy=None, like=None)
+
+ Convert the input to an ndarray, but pass ndarray subclasses through.
+
+ Parameters
+ ----------
+ a : array_like
+ Input data, in any form that can be converted to an array. This
+ includes scalars, lists, lists of tuples, tuples, tuples of tuples,
+ tuples of lists, and ndarrays.
+ dtype : data-type, optional
+ By default, the data-type is inferred from the input data.
+ order : {'C', 'F', 'A', 'K'}, optional
+ Memory layout. 'A' and 'K' depend on the order of input array a.
+ 'C' row-major (C-style),
+ 'F' column-major (Fortran-style) memory representation.
+ 'A' (any) means 'F' if `a` is Fortran contiguous, 'C' otherwise
+ 'K' (keep) preserve input order
+ Defaults to 'C'.
+ device : str, optional
+ The device on which to place the created array. Default: ``None``.
+ For Array-API interoperability only, so must be ``"cpu"`` if passed.
+
+ .. versionadded:: 2.1.0
+
+ copy : bool, optional
+ If ``True``, then the object is copied. If ``None`` then the object is
+ copied only if needed, i.e. if ``__array__`` returns a copy, if obj
+ is a nested sequence, or if a copy is needed to satisfy any of
+ the other requirements (``dtype``, ``order``, etc.).
+ For ``False`` it raises a ``ValueError`` if a copy cannot be avoided.
+ Default: ``None``.
+
+ .. versionadded:: 2.1.0
+
+ ${ARRAY_FUNCTION_LIKE}
+
+ .. versionadded:: 1.20.0
+
+ Returns
+ -------
+ out : ndarray or an ndarray subclass
+ Array interpretation of `a`. If `a` is an ndarray or a subclass
+ of ndarray, it is returned as-is and no copy is performed.
+
+ See Also
+ --------
+ asarray : Similar function which always returns ndarrays.
+ ascontiguousarray : Convert input to a contiguous array.
+ asfortranarray : Convert input to an ndarray with column-major
+ memory order.
+ asarray_chkfinite : Similar function which checks input for NaNs and
+ Infs.
+ fromiter : Create an array from an iterator.
+ fromfunction : Construct an array by executing a function on grid
+ positions.
+
+ Examples
+ --------
+ Convert a list into an array:
+
+ >>> a = [1, 2]
+ >>> import numpy as np
+ >>> np.asanyarray(a)
+ array([1, 2])
+
+ Instances of `ndarray` subclasses are passed through as-is:
+
+ >>> a = np.array([(1., 2), (3., 4)], dtype='f4,i4').view(np.recarray)
+ >>> np.asanyarray(a) is a
+ True
+
+ """)
+
+add_newdoc('numpy._core.multiarray', 'ascontiguousarray',
+ """
+ ascontiguousarray(a, dtype=None, *, like=None)
+
+ Return a contiguous array (ndim >= 1) in memory (C order).
+
+ Parameters
+ ----------
+ a : array_like
+ Input array.
+ dtype : str or dtype object, optional
+ Data-type of returned array.
+ ${ARRAY_FUNCTION_LIKE}
+
+ .. versionadded:: 1.20.0
+
+ Returns
+ -------
+ out : ndarray
+ Contiguous array of same shape and content as `a`, with type `dtype`
+ if specified.
+
+ See Also
+ --------
+ asfortranarray : Convert input to an ndarray with column-major
+ memory order.
+ require : Return an ndarray that satisfies requirements.
+ ndarray.flags : Information about the memory layout of the array.
+
+ Examples
+ --------
+ Starting with a Fortran-contiguous array:
+
+ >>> import numpy as np
+ >>> x = np.ones((2, 3), order='F')
+ >>> x.flags['F_CONTIGUOUS']
+ True
+
+ Calling ``ascontiguousarray`` makes a C-contiguous copy:
+
+ >>> y = np.ascontiguousarray(x)
+ >>> y.flags['C_CONTIGUOUS']
+ True
+ >>> np.may_share_memory(x, y)
+ False
+
+ Now, starting with a C-contiguous array:
+
+ >>> x = np.ones((2, 3), order='C')
+ >>> x.flags['C_CONTIGUOUS']
+ True
+
+ Then, calling ``ascontiguousarray`` returns the same object:
+
+ >>> y = np.ascontiguousarray(x)
+ >>> x is y
+ True
+
+ Note: This function returns an array with at least one-dimension (1-d)
+ so it will not preserve 0-d arrays.
+
+ """)
+
+add_newdoc('numpy._core.multiarray', 'asfortranarray',
+ """
+ asfortranarray(a, dtype=None, *, like=None)
+
+ Return an array (ndim >= 1) laid out in Fortran order in memory.
+
+ Parameters
+ ----------
+ a : array_like
+ Input array.
+ dtype : str or dtype object, optional
+ By default, the data-type is inferred from the input data.
+ ${ARRAY_FUNCTION_LIKE}
+
+ .. versionadded:: 1.20.0
+
+ Returns
+ -------
+ out : ndarray
+ The input `a` in Fortran, or column-major, order.
+
+ See Also
+ --------
+ ascontiguousarray : Convert input to a contiguous (C order) array.
+ asanyarray : Convert input to an ndarray with either row or
+ column-major memory order.
+ require : Return an ndarray that satisfies requirements.
+ ndarray.flags : Information about the memory layout of the array.
+
+ Examples
+ --------
+ Starting with a C-contiguous array:
+
+ >>> import numpy as np
+ >>> x = np.ones((2, 3), order='C')
+ >>> x.flags['C_CONTIGUOUS']
+ True
+
+ Calling ``asfortranarray`` makes a Fortran-contiguous copy:
+
+ >>> y = np.asfortranarray(x)
+ >>> y.flags['F_CONTIGUOUS']
+ True
+ >>> np.may_share_memory(x, y)
+ False
+
+ Now, starting with a Fortran-contiguous array:
+
+ >>> x = np.ones((2, 3), order='F')
+ >>> x.flags['F_CONTIGUOUS']
+ True
+
+ Then, calling ``asfortranarray`` returns the same object:
+
+ >>> y = np.asfortranarray(x)
+ >>> x is y
+ True
+
+ Note: This function returns an array with at least one-dimension (1-d)
+ so it will not preserve 0-d arrays.
+
+ """)
+
+add_newdoc('numpy._core.multiarray', 'empty',
+ """
+ empty(shape, dtype=float, order='C', *, device=None, like=None)
+
+ Return a new array of given shape and type, without initializing entries.
+
+ Parameters
+ ----------
+ shape : int or tuple of int
+ Shape of the empty array, e.g., ``(2, 3)`` or ``2``.
+ dtype : data-type, optional
+ Desired output data-type for the array, e.g, `numpy.int8`. Default is
+ `numpy.float64`.
+ order : {'C', 'F'}, optional, default: 'C'
+ Whether to store multi-dimensional data in row-major
+ (C-style) or column-major (Fortran-style) order in
+ memory.
+ device : str, optional
+ The device on which to place the created array. Default: ``None``.
+ For Array-API interoperability only, so must be ``"cpu"`` if passed.
+
+ .. versionadded:: 2.0.0
+ ${ARRAY_FUNCTION_LIKE}
+
+ .. versionadded:: 1.20.0
+
+ Returns
+ -------
+ out : ndarray
+ Array of uninitialized (arbitrary) data of the given shape, dtype, and
+ order. Object arrays will be initialized to None.
+
+ See Also
+ --------
+ empty_like : Return an empty array with shape and type of input.
+ ones : Return a new array setting values to one.
+ zeros : Return a new array setting values to zero.
+ full : Return a new array of given shape filled with value.
+
+ Notes
+ -----
+ Unlike other array creation functions (e.g. `zeros`, `ones`, `full`),
+ `empty` does not initialize the values of the array, and may therefore be
+ marginally faster. However, the values stored in the newly allocated array
+ are arbitrary. For reproducible behavior, be sure to set each element of
+ the array before reading.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.empty([2, 2])
+ array([[ -9.74499359e+001, 6.69583040e-309],
+ [ 2.13182611e-314, 3.06959433e-309]]) #uninitialized
+
+ >>> np.empty([2, 2], dtype=int)
+ array([[-1073741821, -1067949133],
+ [ 496041986, 19249760]]) #uninitialized
+
+ """)
+
+add_newdoc('numpy._core.multiarray', 'scalar',
+ """
+ scalar(dtype, obj)
+
+ Return a new scalar array of the given type initialized with obj.
+
+ This function is meant mainly for pickle support. `dtype` must be a
+ valid data-type descriptor. If `dtype` corresponds to an object
+ descriptor, then `obj` can be any object, otherwise `obj` must be a
+ string. If `obj` is not given, it will be interpreted as None for object
+ type and as zeros for all other types.
+
+ """)
+
+add_newdoc('numpy._core.multiarray', 'zeros',
+ """
+ zeros(shape, dtype=float, order='C', *, like=None)
+
+ Return a new array of given shape and type, filled with zeros.
+
+ Parameters
+ ----------
+ shape : int or tuple of ints
+ Shape of the new array, e.g., ``(2, 3)`` or ``2``.
+ dtype : data-type, optional
+ The desired data-type for the array, e.g., `numpy.int8`. Default is
+ `numpy.float64`.
+ order : {'C', 'F'}, optional, default: 'C'
+ Whether to store multi-dimensional data in row-major
+ (C-style) or column-major (Fortran-style) order in
+ memory.
+ ${ARRAY_FUNCTION_LIKE}
+
+ .. versionadded:: 1.20.0
+
+ Returns
+ -------
+ out : ndarray
+ Array of zeros with the given shape, dtype, and order.
+
+ See Also
+ --------
+ zeros_like : Return an array of zeros with shape and type of input.
+ empty : Return a new uninitialized array.
+ ones : Return a new array setting values to one.
+ full : Return a new array of given shape filled with value.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.zeros(5)
+ array([ 0., 0., 0., 0., 0.])
+
+ >>> np.zeros((5,), dtype=int)
+ array([0, 0, 0, 0, 0])
+
+ >>> np.zeros((2, 1))
+ array([[ 0.],
+ [ 0.]])
+
+ >>> s = (2,2)
+ >>> np.zeros(s)
+ array([[ 0., 0.],
+ [ 0., 0.]])
+
+ >>> np.zeros((2,), dtype=[('x', 'i4'), ('y', 'i4')]) # custom dtype
+ array([(0, 0), (0, 0)],
+ dtype=[('x', '>> import numpy as np
+ >>> np.fromstring('1 2', dtype=int, sep=' ')
+ array([1, 2])
+ >>> np.fromstring('1, 2', dtype=int, sep=',')
+ array([1, 2])
+
+ """)
+
+add_newdoc('numpy._core.multiarray', 'compare_chararrays',
+ """
+ compare_chararrays(a1, a2, cmp, rstrip)
+
+ Performs element-wise comparison of two string arrays using the
+ comparison operator specified by `cmp`.
+
+ Parameters
+ ----------
+ a1, a2 : array_like
+ Arrays to be compared.
+ cmp : {"<", "<=", "==", ">=", ">", "!="}
+ Type of comparison.
+ rstrip : Boolean
+ If True, the spaces at the end of Strings are removed before the comparison.
+
+ Returns
+ -------
+ out : ndarray
+ The output array of type Boolean with the same shape as a and b.
+
+ Raises
+ ------
+ ValueError
+ If `cmp` is not valid.
+ TypeError
+ If at least one of `a` or `b` is a non-string array
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array(["a", "b", "cde"])
+ >>> b = np.array(["a", "a", "dec"])
+ >>> np.char.compare_chararrays(a, b, ">", True)
+ array([False, True, False])
+
+ """)
+
+add_newdoc('numpy._core.multiarray', 'fromiter',
+ """
+ fromiter(iter, dtype, count=-1, *, like=None)
+
+ Create a new 1-dimensional array from an iterable object.
+
+ Parameters
+ ----------
+ iter : iterable object
+ An iterable object providing data for the array.
+ dtype : data-type
+ The data-type of the returned array.
+
+ .. versionchanged:: 1.23
+ Object and subarray dtypes are now supported (note that the final
+ result is not 1-D for a subarray dtype).
+
+ count : int, optional
+ The number of items to read from *iterable*. The default is -1,
+ which means all data is read.
+ ${ARRAY_FUNCTION_LIKE}
+
+ .. versionadded:: 1.20.0
+
+ Returns
+ -------
+ out : ndarray
+ The output array.
+
+ Notes
+ -----
+ Specify `count` to improve performance. It allows ``fromiter`` to
+ pre-allocate the output array, instead of resizing it on demand.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> iterable = (x*x for x in range(5))
+ >>> np.fromiter(iterable, float)
+ array([ 0., 1., 4., 9., 16.])
+
+ A carefully constructed subarray dtype will lead to higher dimensional
+ results:
+
+ >>> iterable = ((x+1, x+2) for x in range(5))
+ >>> np.fromiter(iterable, dtype=np.dtype((int, 2)))
+ array([[1, 2],
+ [2, 3],
+ [3, 4],
+ [4, 5],
+ [5, 6]])
+
+
+ """)
+
+add_newdoc('numpy._core.multiarray', 'fromfile',
+ """
+ fromfile(file, dtype=float, count=-1, sep='', offset=0, *, like=None)
+
+ Construct an array from data in a text or binary file.
+
+ A highly efficient way of reading binary data with a known data-type,
+ as well as parsing simply formatted text files. Data written using the
+ `tofile` method can be read using this function.
+
+ Parameters
+ ----------
+ file : file or str or Path
+ Open file object or filename.
+ dtype : data-type
+ Data type of the returned array.
+ For binary files, it is used to determine the size and byte-order
+ of the items in the file.
+ Most builtin numeric types are supported and extension types may be supported.
+ count : int
+ Number of items to read. ``-1`` means all items (i.e., the complete
+ file).
+ sep : str
+ Separator between items if file is a text file.
+ Empty ("") separator means the file should be treated as binary.
+ Spaces (" ") in the separator match zero or more whitespace characters.
+ A separator consisting only of spaces must match at least one
+ whitespace.
+ offset : int
+ The offset (in bytes) from the file's current position. Defaults to 0.
+ Only permitted for binary files.
+ ${ARRAY_FUNCTION_LIKE}
+
+ .. versionadded:: 1.20.0
+
+ See also
+ --------
+ load, save
+ ndarray.tofile
+ loadtxt : More flexible way of loading data from a text file.
+
+ Notes
+ -----
+ Do not rely on the combination of `tofile` and `fromfile` for
+ data storage, as the binary files generated are not platform
+ independent. In particular, no byte-order or data-type information is
+ saved. Data can be stored in the platform independent ``.npy`` format
+ using `save` and `load` instead.
+
+ Examples
+ --------
+ Construct an ndarray:
+
+ >>> import numpy as np
+ >>> dt = np.dtype([('time', [('min', np.int64), ('sec', np.int64)]),
+ ... ('temp', float)])
+ >>> x = np.zeros((1,), dtype=dt)
+ >>> x['time']['min'] = 10; x['temp'] = 98.25
+ >>> x
+ array([((10, 0), 98.25)],
+ dtype=[('time', [('min', '>> import tempfile
+ >>> fname = tempfile.mkstemp()[1]
+ >>> x.tofile(fname)
+
+ Read the raw data from disk:
+
+ >>> np.fromfile(fname, dtype=dt)
+ array([((10, 0), 98.25)],
+ dtype=[('time', [('min', '>> np.save(fname, x)
+ >>> np.load(fname + '.npy')
+ array([((10, 0), 98.25)],
+ dtype=[('time', [('min', '>> dt = np.dtype(int)
+ >>> dt = dt.newbyteorder('>')
+ >>> np.frombuffer(buf, dtype=dt) # doctest: +SKIP
+
+ The data of the resulting array will not be byteswapped, but will be
+ interpreted correctly.
+
+ This function creates a view into the original object. This should be safe
+ in general, but it may make sense to copy the result when the original
+ object is mutable or untrusted.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> s = b'hello world'
+ >>> np.frombuffer(s, dtype='S1', count=5, offset=6)
+ array([b'w', b'o', b'r', b'l', b'd'], dtype='|S1')
+
+ >>> np.frombuffer(b'\\x01\\x02', dtype=np.uint8)
+ array([1, 2], dtype=uint8)
+ >>> np.frombuffer(b'\\x01\\x02\\x03\\x04\\x05', dtype=np.uint8, count=3)
+ array([1, 2, 3], dtype=uint8)
+
+ """)
+
+add_newdoc('numpy._core.multiarray', 'from_dlpack',
+ """
+ from_dlpack(x, /, *, device=None, copy=None)
+
+ Create a NumPy array from an object implementing the ``__dlpack__``
+ protocol. Generally, the returned NumPy array is a view of the input
+ object. See [1]_ and [2]_ for more details.
+
+ Parameters
+ ----------
+ x : object
+ A Python object that implements the ``__dlpack__`` and
+ ``__dlpack_device__`` methods.
+ device : device, optional
+ Device on which to place the created array. Default: ``None``.
+ Must be ``"cpu"`` if passed which may allow importing an array
+ that is not already CPU available.
+ copy : bool, optional
+ Boolean indicating whether or not to copy the input. If ``True``,
+ the copy will be made. If ``False``, the function will never copy,
+ and will raise ``BufferError`` in case a copy is deemed necessary.
+ Passing it requests a copy from the exporter who may or may not
+ implement the capability.
+ If ``None``, the function will reuse the existing memory buffer if
+ possible and copy otherwise. Default: ``None``.
+
+
+ Returns
+ -------
+ out : ndarray
+
+ References
+ ----------
+ .. [1] Array API documentation,
+ https://data-apis.org/array-api/latest/design_topics/data_interchange.html#syntax-for-data-interchange-with-dlpack
+
+ .. [2] Python specification for DLPack,
+ https://dmlc.github.io/dlpack/latest/python_spec.html
+
+ Examples
+ --------
+ >>> import torch # doctest: +SKIP
+ >>> x = torch.arange(10) # doctest: +SKIP
+ >>> # create a view of the torch tensor "x" in NumPy
+ >>> y = np.from_dlpack(x) # doctest: +SKIP
+ """)
+
+add_newdoc('numpy._core.multiarray', 'correlate',
+ """cross_correlate(a,v, mode=0)""")
+
+add_newdoc('numpy._core.multiarray', 'arange',
+ """
+ arange([start,] stop[, step,], dtype=None, *, device=None, like=None)
+
+ Return evenly spaced values within a given interval.
+
+ ``arange`` can be called with a varying number of positional arguments:
+
+ * ``arange(stop)``: Values are generated within the half-open interval
+ ``[0, stop)`` (in other words, the interval including `start` but
+ excluding `stop`).
+ * ``arange(start, stop)``: Values are generated within the half-open
+ interval ``[start, stop)``.
+ * ``arange(start, stop, step)`` Values are generated within the half-open
+ interval ``[start, stop)``, with spacing between values given by
+ ``step``.
+
+ For integer arguments the function is roughly equivalent to the Python
+ built-in :py:class:`range`, but returns an ndarray rather than a ``range``
+ instance.
+
+ When using a non-integer step, such as 0.1, it is often better to use
+ `numpy.linspace`.
+
+ See the Warning sections below for more information.
+
+ Parameters
+ ----------
+ start : integer or real, optional
+ Start of interval. The interval includes this value. The default
+ start value is 0.
+ stop : integer or real
+ End of interval. The interval does not include this value, except
+ in some cases where `step` is not an integer and floating point
+ round-off affects the length of `out`.
+ step : integer or real, optional
+ Spacing between values. For any output `out`, this is the distance
+ between two adjacent values, ``out[i+1] - out[i]``. The default
+ step size is 1. If `step` is specified as a position argument,
+ `start` must also be given.
+ dtype : dtype, optional
+ The type of the output array. If `dtype` is not given, infer the data
+ type from the other input arguments.
+ device : str, optional
+ The device on which to place the created array. Default: ``None``.
+ For Array-API interoperability only, so must be ``"cpu"`` if passed.
+
+ .. versionadded:: 2.0.0
+ ${ARRAY_FUNCTION_LIKE}
+
+ .. versionadded:: 1.20.0
+
+ Returns
+ -------
+ arange : ndarray
+ Array of evenly spaced values.
+
+ For floating point arguments, the length of the result is
+ ``ceil((stop - start)/step)``. Because of floating point overflow,
+ this rule may result in the last element of `out` being greater
+ than `stop`.
+
+ Warnings
+ --------
+ The length of the output might not be numerically stable.
+
+ Another stability issue is due to the internal implementation of
+ `numpy.arange`.
+ The actual step value used to populate the array is
+ ``dtype(start + step) - dtype(start)`` and not `step`. Precision loss
+ can occur here, due to casting or due to using floating points when
+ `start` is much larger than `step`. This can lead to unexpected
+ behaviour. For example::
+
+ >>> np.arange(0, 5, 0.5, dtype=int)
+ array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
+ >>> np.arange(-3, 3, 0.5, dtype=int)
+ array([-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8])
+
+ In such cases, the use of `numpy.linspace` should be preferred.
+
+ The built-in :py:class:`range` generates :std:doc:`Python built-in integers
+ that have arbitrary size `, while `numpy.arange`
+ produces `numpy.int32` or `numpy.int64` numbers. This may result in
+ incorrect results for large integer values::
+
+ >>> power = 40
+ >>> modulo = 10000
+ >>> x1 = [(n ** power) % modulo for n in range(8)]
+ >>> x2 = [(n ** power) % modulo for n in np.arange(8)]
+ >>> print(x1)
+ [0, 1, 7776, 8801, 6176, 625, 6576, 4001] # correct
+ >>> print(x2)
+ [0, 1, 7776, 7185, 0, 5969, 4816, 3361] # incorrect
+
+ See Also
+ --------
+ numpy.linspace : Evenly spaced numbers with careful handling of endpoints.
+ numpy.ogrid: Arrays of evenly spaced numbers in N-dimensions.
+ numpy.mgrid: Grid-shaped arrays of evenly spaced numbers in N-dimensions.
+ :ref:`how-to-partition`
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.arange(3)
+ array([0, 1, 2])
+ >>> np.arange(3.0)
+ array([ 0., 1., 2.])
+ >>> np.arange(3,7)
+ array([3, 4, 5, 6])
+ >>> np.arange(3,7,2)
+ array([3, 5])
+
+ """)
+
+add_newdoc('numpy._core.multiarray', '_get_ndarray_c_version',
+ """_get_ndarray_c_version()
+
+ Return the compile time NPY_VERSION (formerly called NDARRAY_VERSION) number.
+
+ """)
+
+add_newdoc('numpy._core.multiarray', '_reconstruct',
+ """_reconstruct(subtype, shape, dtype)
+
+ Construct an empty array. Used by Pickles.
+
+ """)
+
+add_newdoc('numpy._core.multiarray', 'promote_types',
+ """
+ promote_types(type1, type2)
+
+ Returns the data type with the smallest size and smallest scalar
+ kind to which both ``type1`` and ``type2`` may be safely cast.
+ The returned data type is always considered "canonical", this mainly
+ means that the promoted dtype will always be in native byte order.
+
+ This function is symmetric, but rarely associative.
+
+ Parameters
+ ----------
+ type1 : dtype or dtype specifier
+ First data type.
+ type2 : dtype or dtype specifier
+ Second data type.
+
+ Returns
+ -------
+ out : dtype
+ The promoted data type.
+
+ Notes
+ -----
+ Please see `numpy.result_type` for additional information about promotion.
+
+ Starting in NumPy 1.9, promote_types function now returns a valid string
+ length when given an integer or float dtype as one argument and a string
+ dtype as another argument. Previously it always returned the input string
+ dtype, even if it wasn't long enough to store the max integer/float value
+ converted to a string.
+
+ .. versionchanged:: 1.23.0
+
+ NumPy now supports promotion for more structured dtypes. It will now
+ remove unnecessary padding from a structure dtype and promote included
+ fields individually.
+
+ See Also
+ --------
+ result_type, dtype, can_cast
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.promote_types('f4', 'f8')
+ dtype('float64')
+
+ >>> np.promote_types('i8', 'f4')
+ dtype('float64')
+
+ >>> np.promote_types('>i8', '>> np.promote_types('i4', 'S8')
+ dtype('S11')
+
+ An example of a non-associative case:
+
+ >>> p = np.promote_types
+ >>> p('S', p('i1', 'u1'))
+ dtype('S6')
+ >>> p(p('S', 'i1'), 'u1')
+ dtype('S4')
+
+ """)
+
+add_newdoc('numpy._core.multiarray', 'c_einsum',
+ """
+ c_einsum(subscripts, *operands, out=None, dtype=None, order='K',
+ casting='safe')
+
+ *This documentation shadows that of the native python implementation of the `einsum` function,
+ except all references and examples related to the `optimize` argument (v 0.12.0) have been removed.*
+
+ Evaluates the Einstein summation convention on the operands.
+
+ Using the Einstein summation convention, many common multi-dimensional,
+ linear algebraic array operations can be represented in a simple fashion.
+ In *implicit* mode `einsum` computes these values.
+
+ In *explicit* mode, `einsum` provides further flexibility to compute
+ other array operations that might not be considered classical Einstein
+ summation operations, by disabling, or forcing summation over specified
+ subscript labels.
+
+ See the notes and examples for clarification.
+
+ Parameters
+ ----------
+ subscripts : str
+ Specifies the subscripts for summation as comma separated list of
+ subscript labels. An implicit (classical Einstein summation)
+ calculation is performed unless the explicit indicator '->' is
+ included as well as subscript labels of the precise output form.
+ operands : list of array_like
+ These are the arrays for the operation.
+ out : ndarray, optional
+ If provided, the calculation is done into this array.
+ dtype : {data-type, None}, optional
+ If provided, forces the calculation to use the data type specified.
+ Note that you may have to also give a more liberal `casting`
+ parameter to allow the conversions. Default is None.
+ order : {'C', 'F', 'A', 'K'}, optional
+ Controls the memory layout of the output. 'C' means it should
+ be C contiguous. 'F' means it should be Fortran contiguous,
+ 'A' means it should be 'F' if the inputs are all 'F', 'C' otherwise.
+ 'K' means it should be as close to the layout of the inputs as
+ is possible, including arbitrarily permuted axes.
+ Default is 'K'.
+ casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
+ Controls what kind of data casting may occur. Setting this to
+ 'unsafe' is not recommended, as it can adversely affect accumulations.
+
+ * 'no' means the data types should not be cast at all.
+ * 'equiv' means only byte-order changes are allowed.
+ * 'safe' means only casts which can preserve values are allowed.
+ * 'same_kind' means only safe casts or casts within a kind,
+ like float64 to float32, are allowed.
+ * 'unsafe' means any data conversions may be done.
+
+ Default is 'safe'.
+ optimize : {False, True, 'greedy', 'optimal'}, optional
+ Controls if intermediate optimization should occur. No optimization
+ will occur if False and True will default to the 'greedy' algorithm.
+ Also accepts an explicit contraction list from the ``np.einsum_path``
+ function. See ``np.einsum_path`` for more details. Defaults to False.
+
+ Returns
+ -------
+ output : ndarray
+ The calculation based on the Einstein summation convention.
+
+ See Also
+ --------
+ einsum_path, dot, inner, outer, tensordot, linalg.multi_dot
+
+ Notes
+ -----
+ The Einstein summation convention can be used to compute
+ many multi-dimensional, linear algebraic array operations. `einsum`
+ provides a succinct way of representing these.
+
+ A non-exhaustive list of these operations,
+ which can be computed by `einsum`, is shown below along with examples:
+
+ * Trace of an array, :py:func:`numpy.trace`.
+ * Return a diagonal, :py:func:`numpy.diag`.
+ * Array axis summations, :py:func:`numpy.sum`.
+ * Transpositions and permutations, :py:func:`numpy.transpose`.
+ * Matrix multiplication and dot product, :py:func:`numpy.matmul` :py:func:`numpy.dot`.
+ * Vector inner and outer products, :py:func:`numpy.inner` :py:func:`numpy.outer`.
+ * Broadcasting, element-wise and scalar multiplication, :py:func:`numpy.multiply`.
+ * Tensor contractions, :py:func:`numpy.tensordot`.
+ * Chained array operations, in efficient calculation order, :py:func:`numpy.einsum_path`.
+
+ The subscripts string is a comma-separated list of subscript labels,
+ where each label refers to a dimension of the corresponding operand.
+ Whenever a label is repeated it is summed, so ``np.einsum('i,i', a, b)``
+ is equivalent to :py:func:`np.inner(a,b) `. If a label
+ appears only once, it is not summed, so ``np.einsum('i', a)`` produces a
+ view of ``a`` with no changes. A further example ``np.einsum('ij,jk', a, b)``
+ describes traditional matrix multiplication and is equivalent to
+ :py:func:`np.matmul(a,b) `. Repeated subscript labels in one
+ operand take the diagonal. For example, ``np.einsum('ii', a)`` is equivalent
+ to :py:func:`np.trace(a) `.
+
+ In *implicit mode*, the chosen subscripts are important
+ since the axes of the output are reordered alphabetically. This
+ means that ``np.einsum('ij', a)`` doesn't affect a 2D array, while
+ ``np.einsum('ji', a)`` takes its transpose. Additionally,
+ ``np.einsum('ij,jk', a, b)`` returns a matrix multiplication, while,
+ ``np.einsum('ij,jh', a, b)`` returns the transpose of the
+ multiplication since subscript 'h' precedes subscript 'i'.
+
+ In *explicit mode* the output can be directly controlled by
+ specifying output subscript labels. This requires the
+ identifier '->' as well as the list of output subscript labels.
+ This feature increases the flexibility of the function since
+ summing can be disabled or forced when required. The call
+ ``np.einsum('i->', a)`` is like :py:func:`np.sum(a) `
+ if ``a`` is a 1-D array, and ``np.einsum('ii->i', a)``
+ is like :py:func:`np.diag(a) ` if ``a`` is a square 2-D array.
+ The difference is that `einsum` does not allow broadcasting by default.
+ Additionally ``np.einsum('ij,jh->ih', a, b)`` directly specifies the
+ order of the output subscript labels and therefore returns matrix
+ multiplication, unlike the example above in implicit mode.
+
+ To enable and control broadcasting, use an ellipsis. Default
+ NumPy-style broadcasting is done by adding an ellipsis
+ to the left of each term, like ``np.einsum('...ii->...i', a)``.
+ ``np.einsum('...i->...', a)`` is like
+ :py:func:`np.sum(a, axis=-1) ` for array ``a`` of any shape.
+ To take the trace along the first and last axes,
+ you can do ``np.einsum('i...i', a)``, or to do a matrix-matrix
+ product with the left-most indices instead of rightmost, one can do
+ ``np.einsum('ij...,jk...->ik...', a, b)``.
+
+ When there is only one operand, no axes are summed, and no output
+ parameter is provided, a view into the operand is returned instead
+ of a new array. Thus, taking the diagonal as ``np.einsum('ii->i', a)``
+ produces a view (changed in version 1.10.0).
+
+ `einsum` also provides an alternative way to provide the subscripts
+ and operands as ``einsum(op0, sublist0, op1, sublist1, ..., [sublistout])``.
+ If the output shape is not provided in this format `einsum` will be
+ calculated in implicit mode, otherwise it will be performed explicitly.
+ The examples below have corresponding `einsum` calls with the two
+ parameter methods.
+
+ Views returned from einsum are now writeable whenever the input array
+ is writeable. For example, ``np.einsum('ijk...->kji...', a)`` will now
+ have the same effect as :py:func:`np.swapaxes(a, 0, 2) `
+ and ``np.einsum('ii->i', a)`` will return a writeable view of the diagonal
+ of a 2D array.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.arange(25).reshape(5,5)
+ >>> b = np.arange(5)
+ >>> c = np.arange(6).reshape(2,3)
+
+ Trace of a matrix:
+
+ >>> np.einsum('ii', a)
+ 60
+ >>> np.einsum(a, [0,0])
+ 60
+ >>> np.trace(a)
+ 60
+
+ Extract the diagonal (requires explicit form):
+
+ >>> np.einsum('ii->i', a)
+ array([ 0, 6, 12, 18, 24])
+ >>> np.einsum(a, [0,0], [0])
+ array([ 0, 6, 12, 18, 24])
+ >>> np.diag(a)
+ array([ 0, 6, 12, 18, 24])
+
+ Sum over an axis (requires explicit form):
+
+ >>> np.einsum('ij->i', a)
+ array([ 10, 35, 60, 85, 110])
+ >>> np.einsum(a, [0,1], [0])
+ array([ 10, 35, 60, 85, 110])
+ >>> np.sum(a, axis=1)
+ array([ 10, 35, 60, 85, 110])
+
+ For higher dimensional arrays summing a single axis can be done with ellipsis:
+
+ >>> np.einsum('...j->...', a)
+ array([ 10, 35, 60, 85, 110])
+ >>> np.einsum(a, [Ellipsis,1], [Ellipsis])
+ array([ 10, 35, 60, 85, 110])
+
+ Compute a matrix transpose, or reorder any number of axes:
+
+ >>> np.einsum('ji', c)
+ array([[0, 3],
+ [1, 4],
+ [2, 5]])
+ >>> np.einsum('ij->ji', c)
+ array([[0, 3],
+ [1, 4],
+ [2, 5]])
+ >>> np.einsum(c, [1,0])
+ array([[0, 3],
+ [1, 4],
+ [2, 5]])
+ >>> np.transpose(c)
+ array([[0, 3],
+ [1, 4],
+ [2, 5]])
+
+ Vector inner products:
+
+ >>> np.einsum('i,i', b, b)
+ 30
+ >>> np.einsum(b, [0], b, [0])
+ 30
+ >>> np.inner(b,b)
+ 30
+
+ Matrix vector multiplication:
+
+ >>> np.einsum('ij,j', a, b)
+ array([ 30, 80, 130, 180, 230])
+ >>> np.einsum(a, [0,1], b, [1])
+ array([ 30, 80, 130, 180, 230])
+ >>> np.dot(a, b)
+ array([ 30, 80, 130, 180, 230])
+ >>> np.einsum('...j,j', a, b)
+ array([ 30, 80, 130, 180, 230])
+
+ Broadcasting and scalar multiplication:
+
+ >>> np.einsum('..., ...', 3, c)
+ array([[ 0, 3, 6],
+ [ 9, 12, 15]])
+ >>> np.einsum(',ij', 3, c)
+ array([[ 0, 3, 6],
+ [ 9, 12, 15]])
+ >>> np.einsum(3, [Ellipsis], c, [Ellipsis])
+ array([[ 0, 3, 6],
+ [ 9, 12, 15]])
+ >>> np.multiply(3, c)
+ array([[ 0, 3, 6],
+ [ 9, 12, 15]])
+
+ Vector outer product:
+
+ >>> np.einsum('i,j', np.arange(2)+1, b)
+ array([[0, 1, 2, 3, 4],
+ [0, 2, 4, 6, 8]])
+ >>> np.einsum(np.arange(2)+1, [0], b, [1])
+ array([[0, 1, 2, 3, 4],
+ [0, 2, 4, 6, 8]])
+ >>> np.outer(np.arange(2)+1, b)
+ array([[0, 1, 2, 3, 4],
+ [0, 2, 4, 6, 8]])
+
+ Tensor contraction:
+
+ >>> a = np.arange(60.).reshape(3,4,5)
+ >>> b = np.arange(24.).reshape(4,3,2)
+ >>> np.einsum('ijk,jil->kl', a, b)
+ array([[ 4400., 4730.],
+ [ 4532., 4874.],
+ [ 4664., 5018.],
+ [ 4796., 5162.],
+ [ 4928., 5306.]])
+ >>> np.einsum(a, [0,1,2], b, [1,0,3], [2,3])
+ array([[ 4400., 4730.],
+ [ 4532., 4874.],
+ [ 4664., 5018.],
+ [ 4796., 5162.],
+ [ 4928., 5306.]])
+ >>> np.tensordot(a,b, axes=([1,0],[0,1]))
+ array([[ 4400., 4730.],
+ [ 4532., 4874.],
+ [ 4664., 5018.],
+ [ 4796., 5162.],
+ [ 4928., 5306.]])
+
+ Writeable returned arrays (since version 1.10.0):
+
+ >>> a = np.zeros((3, 3))
+ >>> np.einsum('ii->i', a)[:] = 1
+ >>> a
+ array([[ 1., 0., 0.],
+ [ 0., 1., 0.],
+ [ 0., 0., 1.]])
+
+ Example of ellipsis use:
+
+ >>> a = np.arange(6).reshape((3,2))
+ >>> b = np.arange(12).reshape((4,3))
+ >>> np.einsum('ki,jk->ij', a, b)
+ array([[10, 28, 46, 64],
+ [13, 40, 67, 94]])
+ >>> np.einsum('ki,...k->i...', a, b)
+ array([[10, 28, 46, 64],
+ [13, 40, 67, 94]])
+ >>> np.einsum('k...,jk', a, b)
+ array([[10, 28, 46, 64],
+ [13, 40, 67, 94]])
+
+ """)
+
+
+##############################################################################
+#
+# Documentation for ndarray attributes and methods
+#
+##############################################################################
+
+
+##############################################################################
+#
+# ndarray object
+#
+##############################################################################
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray',
+ """
+ ndarray(shape, dtype=float, buffer=None, offset=0,
+ strides=None, order=None)
+
+ An array object represents a multidimensional, homogeneous array
+ of fixed-size items. An associated data-type object describes the
+ format of each element in the array (its byte-order, how many bytes it
+ occupies in memory, whether it is an integer, a floating point number,
+ or something else, etc.)
+
+ Arrays should be constructed using `array`, `zeros` or `empty` (refer
+ to the See Also section below). The parameters given here refer to
+ a low-level method (`ndarray(...)`) for instantiating an array.
+
+ For more information, refer to the `numpy` module and examine the
+ methods and attributes of an array.
+
+ Parameters
+ ----------
+ (for the __new__ method; see Notes below)
+
+ shape : tuple of ints
+ Shape of created array.
+ dtype : data-type, optional
+ Any object that can be interpreted as a numpy data type.
+ buffer : object exposing buffer interface, optional
+ Used to fill the array with data.
+ offset : int, optional
+ Offset of array data in buffer.
+ strides : tuple of ints, optional
+ Strides of data in memory.
+ order : {'C', 'F'}, optional
+ Row-major (C-style) or column-major (Fortran-style) order.
+
+ Attributes
+ ----------
+ T : ndarray
+ Transpose of the array.
+ data : buffer
+ The array's elements, in memory.
+ dtype : dtype object
+ Describes the format of the elements in the array.
+ flags : dict
+ Dictionary containing information related to memory use, e.g.,
+ 'C_CONTIGUOUS', 'OWNDATA', 'WRITEABLE', etc.
+ flat : numpy.flatiter object
+ Flattened version of the array as an iterator. The iterator
+ allows assignments, e.g., ``x.flat = 3`` (See `ndarray.flat` for
+ assignment examples; TODO).
+ imag : ndarray
+ Imaginary part of the array.
+ real : ndarray
+ Real part of the array.
+ size : int
+ Number of elements in the array.
+ itemsize : int
+ The memory use of each array element in bytes.
+ nbytes : int
+ The total number of bytes required to store the array data,
+ i.e., ``itemsize * size``.
+ ndim : int
+ The array's number of dimensions.
+ shape : tuple of ints
+ Shape of the array.
+ strides : tuple of ints
+ The step-size required to move from one element to the next in
+ memory. For example, a contiguous ``(3, 4)`` array of type
+ ``int16`` in C-order has strides ``(8, 2)``. This implies that
+ to move from element to element in memory requires jumps of 2 bytes.
+ To move from row-to-row, one needs to jump 8 bytes at a time
+ (``2 * 4``).
+ ctypes : ctypes object
+ Class containing properties of the array needed for interaction
+ with ctypes.
+ base : ndarray
+ If the array is a view into another array, that array is its `base`
+ (unless that array is also a view). The `base` array is where the
+ array data is actually stored.
+
+ See Also
+ --------
+ array : Construct an array.
+ zeros : Create an array, each element of which is zero.
+ empty : Create an array, but leave its allocated memory unchanged (i.e.,
+ it contains "garbage").
+ dtype : Create a data-type.
+ numpy.typing.NDArray : An ndarray alias :term:`generic `
+ w.r.t. its `dtype.type `.
+
+ Notes
+ -----
+ There are two modes of creating an array using ``__new__``:
+
+ 1. If `buffer` is None, then only `shape`, `dtype`, and `order`
+ are used.
+ 2. If `buffer` is an object exposing the buffer interface, then
+ all keywords are interpreted.
+
+ No ``__init__`` method is needed because the array is fully initialized
+ after the ``__new__`` method.
+
+ Examples
+ --------
+ These examples illustrate the low-level `ndarray` constructor. Refer
+ to the `See Also` section above for easier ways of constructing an
+ ndarray.
+
+ First mode, `buffer` is None:
+
+ >>> import numpy as np
+ >>> np.ndarray(shape=(2,2), dtype=float, order='F')
+ array([[0.0e+000, 0.0e+000], # random
+ [ nan, 2.5e-323]])
+
+ Second mode:
+
+ >>> np.ndarray((2,), buffer=np.array([1,2,3]),
+ ... offset=np.int_().itemsize,
+ ... dtype=int) # offset = 1*itemsize, i.e. skip first element
+ array([2, 3])
+
+ """)
+
+
+##############################################################################
+#
+# ndarray attributes
+#
+##############################################################################
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('__array_interface__',
+ """Array protocol: Python side."""))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('__array_priority__',
+ """Array priority."""))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('__array_struct__',
+ """Array protocol: C-struct side."""))
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('__dlpack__',
+ """
+ a.__dlpack__(*, stream=None, max_version=None, dl_device=None, copy=None)
+
+ DLPack Protocol: Part of the Array API.
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('__dlpack_device__',
+ """
+ a.__dlpack_device__()
+
+ DLPack Protocol: Part of the Array API.
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('base',
+ """
+ Base object if memory is from some other object.
+
+ Examples
+ --------
+ The base of an array that owns its memory is None:
+
+ >>> import numpy as np
+ >>> x = np.array([1,2,3,4])
+ >>> x.base is None
+ True
+
+ Slicing creates a view, whose memory is shared with x:
+
+ >>> y = x[2:]
+ >>> y.base is x
+ True
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('ctypes',
+ """
+ An object to simplify the interaction of the array with the ctypes
+ module.
+
+ This attribute creates an object that makes it easier to use arrays
+ when calling shared libraries with the ctypes module. The returned
+ object has, among others, data, shape, and strides attributes (see
+ Notes below) which themselves return ctypes objects that can be used
+ as arguments to a shared library.
+
+ Parameters
+ ----------
+ None
+
+ Returns
+ -------
+ c : Python object
+ Possessing attributes data, shape, strides, etc.
+
+ See Also
+ --------
+ numpy.ctypeslib
+
+ Notes
+ -----
+ Below are the public attributes of this object which were documented
+ in "Guide to NumPy" (we have omitted undocumented public attributes,
+ as well as documented private attributes):
+
+ .. autoattribute:: numpy._core._internal._ctypes.data
+ :noindex:
+
+ .. autoattribute:: numpy._core._internal._ctypes.shape
+ :noindex:
+
+ .. autoattribute:: numpy._core._internal._ctypes.strides
+ :noindex:
+
+ .. automethod:: numpy._core._internal._ctypes.data_as
+ :noindex:
+
+ .. automethod:: numpy._core._internal._ctypes.shape_as
+ :noindex:
+
+ .. automethod:: numpy._core._internal._ctypes.strides_as
+ :noindex:
+
+ If the ctypes module is not available, then the ctypes attribute
+ of array objects still returns something useful, but ctypes objects
+ are not returned and errors may be raised instead. In particular,
+ the object will still have the ``as_parameter`` attribute which will
+ return an integer equal to the data attribute.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> import ctypes
+ >>> x = np.array([[0, 1], [2, 3]], dtype=np.int32)
+ >>> x
+ array([[0, 1],
+ [2, 3]], dtype=int32)
+ >>> x.ctypes.data
+ 31962608 # may vary
+ >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32))
+ <__main__.LP_c_uint object at 0x7ff2fc1fc200> # may vary
+ >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)).contents
+ c_uint(0)
+ >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint64)).contents
+ c_ulong(4294967296)
+ >>> x.ctypes.shape
+ # may vary
+ >>> x.ctypes.strides
+ # may vary
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('data',
+ """Python buffer object pointing to the start of the array's data."""))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('dtype',
+ """
+ Data-type of the array's elements.
+
+ .. warning::
+
+ Setting ``arr.dtype`` is discouraged and may be deprecated in the
+ future. Setting will replace the ``dtype`` without modifying the
+ memory (see also `ndarray.view` and `ndarray.astype`).
+
+ Parameters
+ ----------
+ None
+
+ Returns
+ -------
+ d : numpy dtype object
+
+ See Also
+ --------
+ ndarray.astype : Cast the values contained in the array to a new data-type.
+ ndarray.view : Create a view of the same data but a different data-type.
+ numpy.dtype
+
+ Examples
+ --------
+ >>> x
+ array([[0, 1],
+ [2, 3]])
+ >>> x.dtype
+ dtype('int32')
+ >>> type(x.dtype)
+
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('imag',
+ """
+ The imaginary part of the array.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.sqrt([1+0j, 0+1j])
+ >>> x.imag
+ array([ 0. , 0.70710678])
+ >>> x.imag.dtype
+ dtype('float64')
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('itemsize',
+ """
+ Length of one array element in bytes.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.array([1,2,3], dtype=np.float64)
+ >>> x.itemsize
+ 8
+ >>> x = np.array([1,2,3], dtype=np.complex128)
+ >>> x.itemsize
+ 16
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('flags',
+ """
+ Information about the memory layout of the array.
+
+ Attributes
+ ----------
+ C_CONTIGUOUS (C)
+ The data is in a single, C-style contiguous segment.
+ F_CONTIGUOUS (F)
+ The data is in a single, Fortran-style contiguous segment.
+ OWNDATA (O)
+ The array owns the memory it uses or borrows it from another object.
+ WRITEABLE (W)
+ The data area can be written to. Setting this to False locks
+ the data, making it read-only. A view (slice, etc.) inherits WRITEABLE
+ from its base array at creation time, but a view of a writeable
+ array may be subsequently locked while the base array remains writeable.
+ (The opposite is not true, in that a view of a locked array may not
+ be made writeable. However, currently, locking a base object does not
+ lock any views that already reference it, so under that circumstance it
+ is possible to alter the contents of a locked array via a previously
+ created writeable view onto it.) Attempting to change a non-writeable
+ array raises a RuntimeError exception.
+ ALIGNED (A)
+ The data and all elements are aligned appropriately for the hardware.
+ WRITEBACKIFCOPY (X)
+ This array is a copy of some other array. The C-API function
+ PyArray_ResolveWritebackIfCopy must be called before deallocating
+ to the base array will be updated with the contents of this array.
+ FNC
+ F_CONTIGUOUS and not C_CONTIGUOUS.
+ FORC
+ F_CONTIGUOUS or C_CONTIGUOUS (one-segment test).
+ BEHAVED (B)
+ ALIGNED and WRITEABLE.
+ CARRAY (CA)
+ BEHAVED and C_CONTIGUOUS.
+ FARRAY (FA)
+ BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS.
+
+ Notes
+ -----
+ The `flags` object can be accessed dictionary-like (as in ``a.flags['WRITEABLE']``),
+ or by using lowercased attribute names (as in ``a.flags.writeable``). Short flag
+ names are only supported in dictionary access.
+
+ Only the WRITEBACKIFCOPY, WRITEABLE, and ALIGNED flags can be
+ changed by the user, via direct assignment to the attribute or dictionary
+ entry, or by calling `ndarray.setflags`.
+
+ The array flags cannot be set arbitrarily:
+
+ - WRITEBACKIFCOPY can only be set ``False``.
+ - ALIGNED can only be set ``True`` if the data is truly aligned.
+ - WRITEABLE can only be set ``True`` if the array owns its own memory
+ or the ultimate owner of the memory exposes a writeable buffer
+ interface or is a string.
+
+ Arrays can be both C-style and Fortran-style contiguous simultaneously.
+ This is clear for 1-dimensional arrays, but can also be true for higher
+ dimensional arrays.
+
+ Even for contiguous arrays a stride for a given dimension
+ ``arr.strides[dim]`` may be *arbitrary* if ``arr.shape[dim] == 1``
+ or the array has no elements.
+ It does *not* generally hold that ``self.strides[-1] == self.itemsize``
+ for C-style contiguous arrays or ``self.strides[0] == self.itemsize`` for
+ Fortran-style contiguous arrays is true.
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('flat',
+ """
+ A 1-D iterator over the array.
+
+ This is a `numpy.flatiter` instance, which acts similarly to, but is not
+ a subclass of, Python's built-in iterator object.
+
+ See Also
+ --------
+ flatten : Return a copy of the array collapsed into one dimension.
+
+ flatiter
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.arange(1, 7).reshape(2, 3)
+ >>> x
+ array([[1, 2, 3],
+ [4, 5, 6]])
+ >>> x.flat[3]
+ 4
+ >>> x.T
+ array([[1, 4],
+ [2, 5],
+ [3, 6]])
+ >>> x.T.flat[3]
+ 5
+ >>> type(x.flat)
+
+
+ An assignment example:
+
+ >>> x.flat = 3; x
+ array([[3, 3, 3],
+ [3, 3, 3]])
+ >>> x.flat[[1,4]] = 1; x
+ array([[3, 1, 3],
+ [3, 1, 3]])
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('nbytes',
+ """
+ Total bytes consumed by the elements of the array.
+
+ Notes
+ -----
+ Does not include memory consumed by non-element attributes of the
+ array object.
+
+ See Also
+ --------
+ sys.getsizeof
+ Memory consumed by the object itself without parents in case view.
+ This does include memory consumed by non-element attributes.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.zeros((3,5,2), dtype=np.complex128)
+ >>> x.nbytes
+ 480
+ >>> np.prod(x.shape) * x.itemsize
+ 480
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('ndim',
+ """
+ Number of array dimensions.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.array([1, 2, 3])
+ >>> x.ndim
+ 1
+ >>> y = np.zeros((2, 3, 4))
+ >>> y.ndim
+ 3
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('real',
+ """
+ The real part of the array.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.sqrt([1+0j, 0+1j])
+ >>> x.real
+ array([ 1. , 0.70710678])
+ >>> x.real.dtype
+ dtype('float64')
+
+ See Also
+ --------
+ numpy.real : equivalent function
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('shape',
+ """
+ Tuple of array dimensions.
+
+ The shape property is usually used to get the current shape of an array,
+ but may also be used to reshape the array in-place by assigning a tuple of
+ array dimensions to it. As with `numpy.reshape`, one of the new shape
+ dimensions can be -1, in which case its value is inferred from the size of
+ the array and the remaining dimensions. Reshaping an array in-place will
+ fail if a copy is required.
+
+ .. warning::
+
+ Setting ``arr.shape`` is discouraged and may be deprecated in the
+ future. Using `ndarray.reshape` is the preferred approach.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.array([1, 2, 3, 4])
+ >>> x.shape
+ (4,)
+ >>> y = np.zeros((2, 3, 4))
+ >>> y.shape
+ (2, 3, 4)
+ >>> y.shape = (3, 8)
+ >>> y
+ array([[ 0., 0., 0., 0., 0., 0., 0., 0.],
+ [ 0., 0., 0., 0., 0., 0., 0., 0.],
+ [ 0., 0., 0., 0., 0., 0., 0., 0.]])
+ >>> y.shape = (3, 6)
+ Traceback (most recent call last):
+ File "", line 1, in
+ ValueError: total size of new array must be unchanged
+ >>> np.zeros((4,2))[::2].shape = (-1,)
+ Traceback (most recent call last):
+ File "", line 1, in
+ AttributeError: Incompatible shape for in-place modification. Use
+ `.reshape()` to make a copy with the desired shape.
+
+ See Also
+ --------
+ numpy.shape : Equivalent getter function.
+ numpy.reshape : Function similar to setting ``shape``.
+ ndarray.reshape : Method similar to setting ``shape``.
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('size',
+ """
+ Number of elements in the array.
+
+ Equal to ``np.prod(a.shape)``, i.e., the product of the array's
+ dimensions.
+
+ Notes
+ -----
+ `a.size` returns a standard arbitrary precision Python integer. This
+ may not be the case with other methods of obtaining the same value
+ (like the suggested ``np.prod(a.shape)``, which returns an instance
+ of ``np.int_``), and may be relevant if the value is used further in
+ calculations that may overflow a fixed size integer type.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.zeros((3, 5, 2), dtype=np.complex128)
+ >>> x.size
+ 30
+ >>> np.prod(x.shape)
+ 30
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('strides',
+ """
+ Tuple of bytes to step in each dimension when traversing an array.
+
+ The byte offset of element ``(i[0], i[1], ..., i[n])`` in an array `a`
+ is::
+
+ offset = sum(np.array(i) * a.strides)
+
+ A more detailed explanation of strides can be found in
+ :ref:`arrays.ndarray`.
+
+ .. warning::
+
+ Setting ``arr.strides`` is discouraged and may be deprecated in the
+ future. `numpy.lib.stride_tricks.as_strided` should be preferred
+ to create a new view of the same data in a safer way.
+
+ Notes
+ -----
+ Imagine an array of 32-bit integers (each 4 bytes)::
+
+ x = np.array([[0, 1, 2, 3, 4],
+ [5, 6, 7, 8, 9]], dtype=np.int32)
+
+ This array is stored in memory as 40 bytes, one after the other
+ (known as a contiguous block of memory). The strides of an array tell
+ us how many bytes we have to skip in memory to move to the next position
+ along a certain axis. For example, we have to skip 4 bytes (1 value) to
+ move to the next column, but 20 bytes (5 values) to get to the same
+ position in the next row. As such, the strides for the array `x` will be
+ ``(20, 4)``.
+
+ See Also
+ --------
+ numpy.lib.stride_tricks.as_strided
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> y = np.reshape(np.arange(2*3*4), (2,3,4))
+ >>> y
+ array([[[ 0, 1, 2, 3],
+ [ 4, 5, 6, 7],
+ [ 8, 9, 10, 11]],
+ [[12, 13, 14, 15],
+ [16, 17, 18, 19],
+ [20, 21, 22, 23]]])
+ >>> y.strides
+ (48, 16, 4)
+ >>> y[1,1,1]
+ 17
+ >>> offset=sum(y.strides * np.array((1,1,1)))
+ >>> offset/y.itemsize
+ 17
+
+ >>> x = np.reshape(np.arange(5*6*7*8), (5,6,7,8)).transpose(2,3,1,0)
+ >>> x.strides
+ (32, 4, 224, 1344)
+ >>> i = np.array([3,5,2,2])
+ >>> offset = sum(i * x.strides)
+ >>> x[3,5,2,2]
+ 813
+ >>> offset / x.itemsize
+ 813
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('T',
+ """
+ View of the transposed array.
+
+ Same as ``self.transpose()``.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[1, 2], [3, 4]])
+ >>> a
+ array([[1, 2],
+ [3, 4]])
+ >>> a.T
+ array([[1, 3],
+ [2, 4]])
+
+ >>> a = np.array([1, 2, 3, 4])
+ >>> a
+ array([1, 2, 3, 4])
+ >>> a.T
+ array([1, 2, 3, 4])
+
+ See Also
+ --------
+ transpose
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('mT',
+ """
+ View of the matrix transposed array.
+
+ The matrix transpose is the transpose of the last two dimensions, even
+ if the array is of higher dimension.
+
+ .. versionadded:: 2.0
+
+ Raises
+ ------
+ ValueError
+ If the array is of dimension less than 2.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[1, 2], [3, 4]])
+ >>> a
+ array([[1, 2],
+ [3, 4]])
+ >>> a.mT
+ array([[1, 3],
+ [2, 4]])
+
+ >>> a = np.arange(8).reshape((2, 2, 2))
+ >>> a
+ array([[[0, 1],
+ [2, 3]],
+
+ [[4, 5],
+ [6, 7]]])
+ >>> a.mT
+ array([[[0, 2],
+ [1, 3]],
+
+ [[4, 6],
+ [5, 7]]])
+
+ """))
+##############################################################################
+#
+# ndarray methods
+#
+##############################################################################
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('__array__',
+ """
+ a.__array__([dtype], *, copy=None)
+
+ For ``dtype`` parameter it returns a new reference to self if
+ ``dtype`` is not given or it matches array's data type.
+ A new array of provided data type is returned if ``dtype``
+ is different from the current data type of the array.
+ For ``copy`` parameter it returns a new reference to self if
+ ``copy=False`` or ``copy=None`` and copying isn't enforced by ``dtype``
+ parameter. The method returns a new array for ``copy=True``, regardless of
+ ``dtype`` parameter.
+
+ A more detailed explanation of the ``__array__`` interface
+ can be found in :ref:`dunder_array.interface`.
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('__array_finalize__',
+ """
+ a.__array_finalize__(obj, /)
+
+ Present so subclasses can call super. Does nothing.
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('__array_wrap__',
+ """
+ a.__array_wrap__(array[, context], /)
+
+ Returns a view of `array` with the same type as self.
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('__copy__',
+ """
+ a.__copy__()
+
+ Used if :func:`copy.copy` is called on an array. Returns a copy of the array.
+
+ Equivalent to ``a.copy(order='K')``.
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('__class_getitem__',
+ """
+ a.__class_getitem__(item, /)
+
+ Return a parametrized wrapper around the `~numpy.ndarray` type.
+
+ .. versionadded:: 1.22
+
+ Returns
+ -------
+ alias : types.GenericAlias
+ A parametrized `~numpy.ndarray` type.
+
+ Examples
+ --------
+ >>> from typing import Any
+ >>> import numpy as np
+
+ >>> np.ndarray[Any, np.dtype[Any]]
+ numpy.ndarray[typing.Any, numpy.dtype[typing.Any]]
+
+ See Also
+ --------
+ :pep:`585` : Type hinting generics in standard collections.
+ numpy.typing.NDArray : An ndarray alias :term:`generic `
+ w.r.t. its `dtype.type `.
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('__deepcopy__',
+ """
+ a.__deepcopy__(memo, /)
+
+ Used if :func:`copy.deepcopy` is called on an array.
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('__reduce__',
+ """
+ a.__reduce__()
+
+ For pickling.
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('__setstate__',
+ """
+ a.__setstate__(state, /)
+
+ For unpickling.
+
+ The `state` argument must be a sequence that contains the following
+ elements:
+
+ Parameters
+ ----------
+ version : int
+ optional pickle version. If omitted defaults to 0.
+ shape : tuple
+ dtype : data-type
+ isFortran : bool
+ rawdata : string or list
+ a binary string with the data (or a list if 'a' is an object array)
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('all',
+ """
+ a.all(axis=None, out=None, keepdims=False, *, where=True)
+
+ Returns True if all elements evaluate to True.
+
+ Refer to `numpy.all` for full documentation.
+
+ See Also
+ --------
+ numpy.all : equivalent function
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('any',
+ """
+ a.any(axis=None, out=None, keepdims=False, *, where=True)
+
+ Returns True if any of the elements of `a` evaluate to True.
+
+ Refer to `numpy.any` for full documentation.
+
+ See Also
+ --------
+ numpy.any : equivalent function
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('argmax',
+ """
+ a.argmax(axis=None, out=None, *, keepdims=False)
+
+ Return indices of the maximum values along the given axis.
+
+ Refer to `numpy.argmax` for full documentation.
+
+ See Also
+ --------
+ numpy.argmax : equivalent function
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('argmin',
+ """
+ a.argmin(axis=None, out=None, *, keepdims=False)
+
+ Return indices of the minimum values along the given axis.
+
+ Refer to `numpy.argmin` for detailed documentation.
+
+ See Also
+ --------
+ numpy.argmin : equivalent function
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('argsort',
+ """
+ a.argsort(axis=-1, kind=None, order=None)
+
+ Returns the indices that would sort this array.
+
+ Refer to `numpy.argsort` for full documentation.
+
+ See Also
+ --------
+ numpy.argsort : equivalent function
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('argpartition',
+ """
+ a.argpartition(kth, axis=-1, kind='introselect', order=None)
+
+ Returns the indices that would partition this array.
+
+ Refer to `numpy.argpartition` for full documentation.
+
+ See Also
+ --------
+ numpy.argpartition : equivalent function
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('astype',
+ """
+ a.astype(dtype, order='K', casting='unsafe', subok=True, copy=True)
+
+ Copy of the array, cast to a specified type.
+
+ Parameters
+ ----------
+ dtype : str or dtype
+ Typecode or data-type to which the array is cast.
+ order : {'C', 'F', 'A', 'K'}, optional
+ Controls the memory layout order of the result.
+ 'C' means C order, 'F' means Fortran order, 'A'
+ means 'F' order if all the arrays are Fortran contiguous,
+ 'C' order otherwise, and 'K' means as close to the
+ order the array elements appear in memory as possible.
+ Default is 'K'.
+ casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
+ Controls what kind of data casting may occur. Defaults to 'unsafe'
+ for backwards compatibility.
+
+ * 'no' means the data types should not be cast at all.
+ * 'equiv' means only byte-order changes are allowed.
+ * 'safe' means only casts which can preserve values are allowed.
+ * 'same_kind' means only safe casts or casts within a kind,
+ like float64 to float32, are allowed.
+ * 'unsafe' means any data conversions may be done.
+ subok : bool, optional
+ If True, then sub-classes will be passed-through (default), otherwise
+ the returned array will be forced to be a base-class array.
+ copy : bool, optional
+ By default, astype always returns a newly allocated array. If this
+ is set to false, and the `dtype`, `order`, and `subok`
+ requirements are satisfied, the input array is returned instead
+ of a copy.
+
+ Returns
+ -------
+ arr_t : ndarray
+ Unless `copy` is False and the other conditions for returning the input
+ array are satisfied (see description for `copy` input parameter), `arr_t`
+ is a new array of the same shape as the input array, with dtype, order
+ given by `dtype`, `order`.
+
+ Raises
+ ------
+ ComplexWarning
+ When casting from complex to float or int. To avoid this,
+ one should use ``a.real.astype(t)``.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.array([1, 2, 2.5])
+ >>> x
+ array([1. , 2. , 2.5])
+
+ >>> x.astype(int)
+ array([1, 2, 2])
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('byteswap',
+ """
+ a.byteswap(inplace=False)
+
+ Swap the bytes of the array elements
+
+ Toggle between low-endian and big-endian data representation by
+ returning a byteswapped array, optionally swapped in-place.
+ Arrays of byte-strings are not swapped. The real and imaginary
+ parts of a complex number are swapped individually.
+
+ Parameters
+ ----------
+ inplace : bool, optional
+ If ``True``, swap bytes in-place, default is ``False``.
+
+ Returns
+ -------
+ out : ndarray
+ The byteswapped array. If `inplace` is ``True``, this is
+ a view to self.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> A = np.array([1, 256, 8755], dtype=np.int16)
+ >>> list(map(hex, A))
+ ['0x1', '0x100', '0x2233']
+ >>> A.byteswap(inplace=True)
+ array([ 256, 1, 13090], dtype=int16)
+ >>> list(map(hex, A))
+ ['0x100', '0x1', '0x3322']
+
+ Arrays of byte-strings are not swapped
+
+ >>> A = np.array([b'ceg', b'fac'])
+ >>> A.byteswap()
+ array([b'ceg', b'fac'], dtype='|S3')
+
+ ``A.view(A.dtype.newbyteorder()).byteswap()`` produces an array with
+ the same values but different representation in memory
+
+ >>> A = np.array([1, 2, 3],dtype=np.int64)
+ >>> A.view(np.uint8)
+ array([1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0,
+ 0, 0], dtype=uint8)
+ >>> A.view(A.dtype.newbyteorder()).byteswap(inplace=True)
+ array([1, 2, 3], dtype='>i8')
+ >>> A.view(np.uint8)
+ array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0,
+ 0, 3], dtype=uint8)
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('choose',
+ """
+ a.choose(choices, out=None, mode='raise')
+
+ Use an index array to construct a new array from a set of choices.
+
+ Refer to `numpy.choose` for full documentation.
+
+ See Also
+ --------
+ numpy.choose : equivalent function
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('clip',
+ """
+ a.clip(min=None, max=None, out=None, **kwargs)
+
+ Return an array whose values are limited to ``[min, max]``.
+ One of max or min must be given.
+
+ Refer to `numpy.clip` for full documentation.
+
+ See Also
+ --------
+ numpy.clip : equivalent function
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('compress',
+ """
+ a.compress(condition, axis=None, out=None)
+
+ Return selected slices of this array along given axis.
+
+ Refer to `numpy.compress` for full documentation.
+
+ See Also
+ --------
+ numpy.compress : equivalent function
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('conj',
+ """
+ a.conj()
+
+ Complex-conjugate all elements.
+
+ Refer to `numpy.conjugate` for full documentation.
+
+ See Also
+ --------
+ numpy.conjugate : equivalent function
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('conjugate',
+ """
+ a.conjugate()
+
+ Return the complex conjugate, element-wise.
+
+ Refer to `numpy.conjugate` for full documentation.
+
+ See Also
+ --------
+ numpy.conjugate : equivalent function
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('copy',
+ """
+ a.copy(order='C')
+
+ Return a copy of the array.
+
+ Parameters
+ ----------
+ order : {'C', 'F', 'A', 'K'}, optional
+ Controls the memory layout of the copy. 'C' means C-order,
+ 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
+ 'C' otherwise. 'K' means match the layout of `a` as closely
+ as possible. (Note that this function and :func:`numpy.copy` are very
+ similar but have different default values for their order=
+ arguments, and this function always passes sub-classes through.)
+
+ See also
+ --------
+ numpy.copy : Similar function with different default behavior
+ numpy.copyto
+
+ Notes
+ -----
+ This function is the preferred method for creating an array copy. The
+ function :func:`numpy.copy` is similar, but it defaults to using order 'K',
+ and will not pass sub-classes through by default.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.array([[1,2,3],[4,5,6]], order='F')
+
+ >>> y = x.copy()
+
+ >>> x.fill(0)
+
+ >>> x
+ array([[0, 0, 0],
+ [0, 0, 0]])
+
+ >>> y
+ array([[1, 2, 3],
+ [4, 5, 6]])
+
+ >>> y.flags['C_CONTIGUOUS']
+ True
+
+ For arrays containing Python objects (e.g. dtype=object),
+ the copy is a shallow one. The new array will contain the
+ same object which may lead to surprises if that object can
+ be modified (is mutable):
+
+ >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
+ >>> b = a.copy()
+ >>> b[2][0] = 10
+ >>> a
+ array([1, 'm', list([10, 3, 4])], dtype=object)
+
+ To ensure all elements within an ``object`` array are copied,
+ use `copy.deepcopy`:
+
+ >>> import copy
+ >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
+ >>> c = copy.deepcopy(a)
+ >>> c[2][0] = 10
+ >>> c
+ array([1, 'm', list([10, 3, 4])], dtype=object)
+ >>> a
+ array([1, 'm', list([2, 3, 4])], dtype=object)
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('cumprod',
+ """
+ a.cumprod(axis=None, dtype=None, out=None)
+
+ Return the cumulative product of the elements along the given axis.
+
+ Refer to `numpy.cumprod` for full documentation.
+
+ See Also
+ --------
+ numpy.cumprod : equivalent function
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('cumsum',
+ """
+ a.cumsum(axis=None, dtype=None, out=None)
+
+ Return the cumulative sum of the elements along the given axis.
+
+ Refer to `numpy.cumsum` for full documentation.
+
+ See Also
+ --------
+ numpy.cumsum : equivalent function
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('diagonal',
+ """
+ a.diagonal(offset=0, axis1=0, axis2=1)
+
+ Return specified diagonals. In NumPy 1.9 the returned array is a
+ read-only view instead of a copy as in previous NumPy versions. In
+ a future version the read-only restriction will be removed.
+
+ Refer to :func:`numpy.diagonal` for full documentation.
+
+ See Also
+ --------
+ numpy.diagonal : equivalent function
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('dot'))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('dump',
+ """
+ a.dump(file)
+
+ Dump a pickle of the array to the specified file.
+ The array can be read back with pickle.load or numpy.load.
+
+ Parameters
+ ----------
+ file : str or Path
+ A string naming the dump file.
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('dumps',
+ """
+ a.dumps()
+
+ Returns the pickle of the array as a string.
+ pickle.loads will convert the string back to an array.
+
+ Parameters
+ ----------
+ None
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('fill',
+ """
+ a.fill(value)
+
+ Fill the array with a scalar value.
+
+ Parameters
+ ----------
+ value : scalar
+ All elements of `a` will be assigned this value.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([1, 2])
+ >>> a.fill(0)
+ >>> a
+ array([0, 0])
+ >>> a = np.empty(2)
+ >>> a.fill(1)
+ >>> a
+ array([1., 1.])
+
+ Fill expects a scalar value and always behaves the same as assigning
+ to a single array element. The following is a rare example where this
+ distinction is important:
+
+ >>> a = np.array([None, None], dtype=object)
+ >>> a[0] = np.array(3)
+ >>> a
+ array([array(3), None], dtype=object)
+ >>> a.fill(np.array(3))
+ >>> a
+ array([array(3), array(3)], dtype=object)
+
+ Where other forms of assignments will unpack the array being assigned:
+
+ >>> a[...] = np.array(3)
+ >>> a
+ array([3, 3], dtype=object)
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('flatten',
+ """
+ a.flatten(order='C')
+
+ Return a copy of the array collapsed into one dimension.
+
+ Parameters
+ ----------
+ order : {'C', 'F', 'A', 'K'}, optional
+ 'C' means to flatten in row-major (C-style) order.
+ 'F' means to flatten in column-major (Fortran-
+ style) order. 'A' means to flatten in column-major
+ order if `a` is Fortran *contiguous* in memory,
+ row-major order otherwise. 'K' means to flatten
+ `a` in the order the elements occur in memory.
+ The default is 'C'.
+
+ Returns
+ -------
+ y : ndarray
+ A copy of the input array, flattened to one dimension.
+
+ See Also
+ --------
+ ravel : Return a flattened array.
+ flat : A 1-D flat iterator over the array.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[1,2], [3,4]])
+ >>> a.flatten()
+ array([1, 2, 3, 4])
+ >>> a.flatten('F')
+ array([1, 3, 2, 4])
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('getfield',
+ """
+ a.getfield(dtype, offset=0)
+
+ Returns a field of the given array as a certain type.
+
+ A field is a view of the array data with a given data-type. The values in
+ the view are determined by the given type and the offset into the current
+ array in bytes. The offset needs to be such that the view dtype fits in the
+ array dtype; for example an array of dtype complex128 has 16-byte elements.
+ If taking a view with a 32-bit integer (4 bytes), the offset needs to be
+ between 0 and 12 bytes.
+
+ Parameters
+ ----------
+ dtype : str or dtype
+ The data type of the view. The dtype size of the view can not be larger
+ than that of the array itself.
+ offset : int
+ Number of bytes to skip before beginning the element view.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.diag([1.+1.j]*2)
+ >>> x[1, 1] = 2 + 4.j
+ >>> x
+ array([[1.+1.j, 0.+0.j],
+ [0.+0.j, 2.+4.j]])
+ >>> x.getfield(np.float64)
+ array([[1., 0.],
+ [0., 2.]])
+
+ By choosing an offset of 8 bytes we can select the complex part of the
+ array for our view:
+
+ >>> x.getfield(np.float64, offset=8)
+ array([[1., 0.],
+ [0., 4.]])
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('item',
+ """
+ a.item(*args)
+
+ Copy an element of an array to a standard Python scalar and return it.
+
+ Parameters
+ ----------
+ \\*args : Arguments (variable number and type)
+
+ * none: in this case, the method only works for arrays
+ with one element (`a.size == 1`), which element is
+ copied into a standard Python scalar object and returned.
+
+ * int_type: this argument is interpreted as a flat index into
+ the array, specifying which element to copy and return.
+
+ * tuple of int_types: functions as does a single int_type argument,
+ except that the argument is interpreted as an nd-index into the
+ array.
+
+ Returns
+ -------
+ z : Standard Python scalar object
+ A copy of the specified element of the array as a suitable
+ Python scalar
+
+ Notes
+ -----
+ When the data type of `a` is longdouble or clongdouble, item() returns
+ a scalar array object because there is no available Python scalar that
+ would not lose information. Void arrays return a buffer object for item(),
+ unless fields are defined, in which case a tuple is returned.
+
+ `item` is very similar to a[args], except, instead of an array scalar,
+ a standard Python scalar is returned. This can be useful for speeding up
+ access to elements of the array and doing arithmetic on elements of the
+ array using Python's optimized math.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.random.seed(123)
+ >>> x = np.random.randint(9, size=(3, 3))
+ >>> x
+ array([[2, 2, 6],
+ [1, 3, 6],
+ [1, 0, 1]])
+ >>> x.item(3)
+ 1
+ >>> x.item(7)
+ 0
+ >>> x.item((0, 1))
+ 2
+ >>> x.item((2, 2))
+ 1
+
+ For an array with object dtype, elements are returned as-is.
+
+ >>> a = np.array([np.int64(1)], dtype=object)
+ >>> a.item() #return np.int64
+ np.int64(1)
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('max',
+ """
+ a.max(axis=None, out=None, keepdims=False, initial=, where=True)
+
+ Return the maximum along a given axis.
+
+ Refer to `numpy.amax` for full documentation.
+
+ See Also
+ --------
+ numpy.amax : equivalent function
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('mean',
+ """
+ a.mean(axis=None, dtype=None, out=None, keepdims=False, *, where=True)
+
+ Returns the average of the array elements along given axis.
+
+ Refer to `numpy.mean` for full documentation.
+
+ See Also
+ --------
+ numpy.mean : equivalent function
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('min',
+ """
+ a.min(axis=None, out=None, keepdims=False, initial=, where=True)
+
+ Return the minimum along a given axis.
+
+ Refer to `numpy.amin` for full documentation.
+
+ See Also
+ --------
+ numpy.amin : equivalent function
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('nonzero',
+ """
+ a.nonzero()
+
+ Return the indices of the elements that are non-zero.
+
+ Refer to `numpy.nonzero` for full documentation.
+
+ See Also
+ --------
+ numpy.nonzero : equivalent function
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('prod',
+ """
+ a.prod(axis=None, dtype=None, out=None, keepdims=False,
+ initial=1, where=True)
+
+ Return the product of the array elements over the given axis
+
+ Refer to `numpy.prod` for full documentation.
+
+ See Also
+ --------
+ numpy.prod : equivalent function
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('put',
+ """
+ a.put(indices, values, mode='raise')
+
+ Set ``a.flat[n] = values[n]`` for all `n` in indices.
+
+ Refer to `numpy.put` for full documentation.
+
+ See Also
+ --------
+ numpy.put : equivalent function
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('ravel',
+ """
+ a.ravel([order])
+
+ Return a flattened array.
+
+ Refer to `numpy.ravel` for full documentation.
+
+ See Also
+ --------
+ numpy.ravel : equivalent function
+
+ ndarray.flat : a flat iterator on the array.
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('repeat',
+ """
+ a.repeat(repeats, axis=None)
+
+ Repeat elements of an array.
+
+ Refer to `numpy.repeat` for full documentation.
+
+ See Also
+ --------
+ numpy.repeat : equivalent function
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('reshape',
+ """
+ a.reshape(shape, /, *, order='C', copy=None)
+
+ Returns an array containing the same data with a new shape.
+
+ Refer to `numpy.reshape` for full documentation.
+
+ See Also
+ --------
+ numpy.reshape : equivalent function
+
+ Notes
+ -----
+ Unlike the free function `numpy.reshape`, this method on `ndarray` allows
+ the elements of the shape parameter to be passed in as separate arguments.
+ For example, ``a.reshape(10, 11)`` is equivalent to
+ ``a.reshape((10, 11))``.
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('resize',
+ """
+ a.resize(new_shape, refcheck=True)
+
+ Change shape and size of array in-place.
+
+ Parameters
+ ----------
+ new_shape : tuple of ints, or `n` ints
+ Shape of resized array.
+ refcheck : bool, optional
+ If False, reference count will not be checked. Default is True.
+
+ Returns
+ -------
+ None
+
+ Raises
+ ------
+ ValueError
+ If `a` does not own its own data or references or views to it exist,
+ and the data memory must be changed.
+ PyPy only: will always raise if the data memory must be changed, since
+ there is no reliable way to determine if references or views to it
+ exist.
+
+ SystemError
+ If the `order` keyword argument is specified. This behaviour is a
+ bug in NumPy.
+
+ See Also
+ --------
+ resize : Return a new array with the specified shape.
+
+ Notes
+ -----
+ This reallocates space for the data area if necessary.
+
+ Only contiguous arrays (data elements consecutive in memory) can be
+ resized.
+
+ The purpose of the reference count check is to make sure you
+ do not use this array as a buffer for another Python object and then
+ reallocate the memory. However, reference counts can increase in
+ other ways so if you are sure that you have not shared the memory
+ for this array with another Python object, then you may safely set
+ `refcheck` to False.
+
+ Examples
+ --------
+ Shrinking an array: array is flattened (in the order that the data are
+ stored in memory), resized, and reshaped:
+
+ >>> import numpy as np
+
+ >>> a = np.array([[0, 1], [2, 3]], order='C')
+ >>> a.resize((2, 1))
+ >>> a
+ array([[0],
+ [1]])
+
+ >>> a = np.array([[0, 1], [2, 3]], order='F')
+ >>> a.resize((2, 1))
+ >>> a
+ array([[0],
+ [2]])
+
+ Enlarging an array: as above, but missing entries are filled with zeros:
+
+ >>> b = np.array([[0, 1], [2, 3]])
+ >>> b.resize(2, 3) # new_shape parameter doesn't have to be a tuple
+ >>> b
+ array([[0, 1, 2],
+ [3, 0, 0]])
+
+ Referencing an array prevents resizing...
+
+ >>> c = a
+ >>> a.resize((1, 1))
+ Traceback (most recent call last):
+ ...
+ ValueError: cannot resize an array that references or is referenced ...
+
+ Unless `refcheck` is False:
+
+ >>> a.resize((1, 1), refcheck=False)
+ >>> a
+ array([[0]])
+ >>> c
+ array([[0]])
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('round',
+ """
+ a.round(decimals=0, out=None)
+
+ Return `a` with each element rounded to the given number of decimals.
+
+ Refer to `numpy.around` for full documentation.
+
+ See Also
+ --------
+ numpy.around : equivalent function
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('searchsorted',
+ """
+ a.searchsorted(v, side='left', sorter=None)
+
+ Find indices where elements of v should be inserted in a to maintain order.
+
+ For full documentation, see `numpy.searchsorted`
+
+ See Also
+ --------
+ numpy.searchsorted : equivalent function
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('setfield',
+ """
+ a.setfield(val, dtype, offset=0)
+
+ Put a value into a specified place in a field defined by a data-type.
+
+ Place `val` into `a`'s field defined by `dtype` and beginning `offset`
+ bytes into the field.
+
+ Parameters
+ ----------
+ val : object
+ Value to be placed in field.
+ dtype : dtype object
+ Data-type of the field in which to place `val`.
+ offset : int, optional
+ The number of bytes into the field at which to place `val`.
+
+ Returns
+ -------
+ None
+
+ See Also
+ --------
+ getfield
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.eye(3)
+ >>> x.getfield(np.float64)
+ array([[1., 0., 0.],
+ [0., 1., 0.],
+ [0., 0., 1.]])
+ >>> x.setfield(3, np.int32)
+ >>> x.getfield(np.int32)
+ array([[3, 3, 3],
+ [3, 3, 3],
+ [3, 3, 3]], dtype=int32)
+ >>> x
+ array([[1.0e+000, 1.5e-323, 1.5e-323],
+ [1.5e-323, 1.0e+000, 1.5e-323],
+ [1.5e-323, 1.5e-323, 1.0e+000]])
+ >>> x.setfield(np.eye(3), np.int32)
+ >>> x
+ array([[1., 0., 0.],
+ [0., 1., 0.],
+ [0., 0., 1.]])
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('setflags',
+ """
+ a.setflags(write=None, align=None, uic=None)
+
+ Set array flags WRITEABLE, ALIGNED, WRITEBACKIFCOPY,
+ respectively.
+
+ These Boolean-valued flags affect how numpy interprets the memory
+ area used by `a` (see Notes below). The ALIGNED flag can only
+ be set to True if the data is actually aligned according to the type.
+ The WRITEBACKIFCOPY flag can never be set
+ to True. The flag WRITEABLE can only be set to True if the array owns its
+ own memory, or the ultimate owner of the memory exposes a writeable buffer
+ interface, or is a string. (The exception for string is made so that
+ unpickling can be done without copying memory.)
+
+ Parameters
+ ----------
+ write : bool, optional
+ Describes whether or not `a` can be written to.
+ align : bool, optional
+ Describes whether or not `a` is aligned properly for its type.
+ uic : bool, optional
+ Describes whether or not `a` is a copy of another "base" array.
+
+ Notes
+ -----
+ Array flags provide information about how the memory area used
+ for the array is to be interpreted. There are 7 Boolean flags
+ in use, only three of which can be changed by the user:
+ WRITEBACKIFCOPY, WRITEABLE, and ALIGNED.
+
+ WRITEABLE (W) the data area can be written to;
+
+ ALIGNED (A) the data and strides are aligned appropriately for the hardware
+ (as determined by the compiler);
+
+ WRITEBACKIFCOPY (X) this array is a copy of some other array (referenced
+ by .base). When the C-API function PyArray_ResolveWritebackIfCopy is
+ called, the base array will be updated with the contents of this array.
+
+ All flags can be accessed using the single (upper case) letter as well
+ as the full name.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> y = np.array([[3, 1, 7],
+ ... [2, 0, 0],
+ ... [8, 5, 9]])
+ >>> y
+ array([[3, 1, 7],
+ [2, 0, 0],
+ [8, 5, 9]])
+ >>> y.flags
+ C_CONTIGUOUS : True
+ F_CONTIGUOUS : False
+ OWNDATA : True
+ WRITEABLE : True
+ ALIGNED : True
+ WRITEBACKIFCOPY : False
+ >>> y.setflags(write=0, align=0)
+ >>> y.flags
+ C_CONTIGUOUS : True
+ F_CONTIGUOUS : False
+ OWNDATA : True
+ WRITEABLE : False
+ ALIGNED : False
+ WRITEBACKIFCOPY : False
+ >>> y.setflags(uic=1)
+ Traceback (most recent call last):
+ File "", line 1, in
+ ValueError: cannot set WRITEBACKIFCOPY flag to True
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('sort',
+ """
+ a.sort(axis=-1, kind=None, order=None)
+
+ Sort an array in-place. Refer to `numpy.sort` for full documentation.
+
+ Parameters
+ ----------
+ axis : int, optional
+ Axis along which to sort. Default is -1, which means sort along the
+ last axis.
+ kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
+ Sorting algorithm. The default is 'quicksort'. Note that both 'stable'
+ and 'mergesort' use timsort under the covers and, in general, the
+ actual implementation will vary with datatype. The 'mergesort' option
+ is retained for backwards compatibility.
+ order : str or list of str, optional
+ When `a` is an array with fields defined, this argument specifies
+ which fields to compare first, second, etc. A single field can
+ be specified as a string, and not all fields need be specified,
+ but unspecified fields will still be used, in the order in which
+ they come up in the dtype, to break ties.
+
+ See Also
+ --------
+ numpy.sort : Return a sorted copy of an array.
+ numpy.argsort : Indirect sort.
+ numpy.lexsort : Indirect stable sort on multiple keys.
+ numpy.searchsorted : Find elements in sorted array.
+ numpy.partition: Partial sort.
+
+ Notes
+ -----
+ See `numpy.sort` for notes on the different sorting algorithms.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[1,4], [3,1]])
+ >>> a.sort(axis=1)
+ >>> a
+ array([[1, 4],
+ [1, 3]])
+ >>> a.sort(axis=0)
+ >>> a
+ array([[1, 3],
+ [1, 4]])
+
+ Use the `order` keyword to specify a field to use when sorting a
+ structured array:
+
+ >>> a = np.array([('a', 2), ('c', 1)], dtype=[('x', 'S1'), ('y', int)])
+ >>> a.sort(order='y')
+ >>> a
+ array([(b'c', 1), (b'a', 2)],
+ dtype=[('x', 'S1'), ('y', '>> import numpy as np
+ >>> a = np.array([3, 4, 2, 1])
+ >>> a.partition(3)
+ >>> a
+ array([2, 1, 3, 4]) # may vary
+
+ >>> a.partition((1, 3))
+ >>> a
+ array([1, 2, 3, 4])
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('squeeze',
+ """
+ a.squeeze(axis=None)
+
+ Remove axes of length one from `a`.
+
+ Refer to `numpy.squeeze` for full documentation.
+
+ See Also
+ --------
+ numpy.squeeze : equivalent function
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('std',
+ """
+ a.std(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True)
+
+ Returns the standard deviation of the array elements along given axis.
+
+ Refer to `numpy.std` for full documentation.
+
+ See Also
+ --------
+ numpy.std : equivalent function
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('sum',
+ """
+ a.sum(axis=None, dtype=None, out=None, keepdims=False, initial=0, where=True)
+
+ Return the sum of the array elements over the given axis.
+
+ Refer to `numpy.sum` for full documentation.
+
+ See Also
+ --------
+ numpy.sum : equivalent function
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('swapaxes',
+ """
+ a.swapaxes(axis1, axis2)
+
+ Return a view of the array with `axis1` and `axis2` interchanged.
+
+ Refer to `numpy.swapaxes` for full documentation.
+
+ See Also
+ --------
+ numpy.swapaxes : equivalent function
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('take',
+ """
+ a.take(indices, axis=None, out=None, mode='raise')
+
+ Return an array formed from the elements of `a` at the given indices.
+
+ Refer to `numpy.take` for full documentation.
+
+ See Also
+ --------
+ numpy.take : equivalent function
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('tofile',
+ """
+ a.tofile(fid, sep="", format="%s")
+
+ Write array to a file as text or binary (default).
+
+ Data is always written in 'C' order, independent of the order of `a`.
+ The data produced by this method can be recovered using the function
+ fromfile().
+
+ Parameters
+ ----------
+ fid : file or str or Path
+ An open file object, or a string containing a filename.
+ sep : str
+ Separator between array items for text output.
+ If "" (empty), a binary file is written, equivalent to
+ ``file.write(a.tobytes())``.
+ format : str
+ Format string for text file output.
+ Each entry in the array is formatted to text by first converting
+ it to the closest Python type, and then using "format" % item.
+
+ Notes
+ -----
+ This is a convenience function for quick storage of array data.
+ Information on endianness and precision is lost, so this method is not a
+ good choice for files intended to archive data or transport data between
+ machines with different endianness. Some of these problems can be overcome
+ by outputting the data as text files, at the expense of speed and file
+ size.
+
+ When fid is a file object, array contents are directly written to the
+ file, bypassing the file object's ``write`` method. As a result, tofile
+ cannot be used with files objects supporting compression (e.g., GzipFile)
+ or file-like objects that do not support ``fileno()`` (e.g., BytesIO).
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('tolist',
+ """
+ a.tolist()
+
+ Return the array as an ``a.ndim``-levels deep nested list of Python scalars.
+
+ Return a copy of the array data as a (nested) Python list.
+ Data items are converted to the nearest compatible builtin Python type, via
+ the `~numpy.ndarray.item` function.
+
+ If ``a.ndim`` is 0, then since the depth of the nested list is 0, it will
+ not be a list at all, but a simple Python scalar.
+
+ Parameters
+ ----------
+ none
+
+ Returns
+ -------
+ y : object, or list of object, or list of list of object, or ...
+ The possibly nested list of array elements.
+
+ Notes
+ -----
+ The array may be recreated via ``a = np.array(a.tolist())``, although this
+ may sometimes lose precision.
+
+ Examples
+ --------
+ For a 1D array, ``a.tolist()`` is almost the same as ``list(a)``,
+ except that ``tolist`` changes numpy scalars to Python scalars:
+
+ >>> import numpy as np
+ >>> a = np.uint32([1, 2])
+ >>> a_list = list(a)
+ >>> a_list
+ [np.uint32(1), np.uint32(2)]
+ >>> type(a_list[0])
+
+ >>> a_tolist = a.tolist()
+ >>> a_tolist
+ [1, 2]
+ >>> type(a_tolist[0])
+
+
+ Additionally, for a 2D array, ``tolist`` applies recursively:
+
+ >>> a = np.array([[1, 2], [3, 4]])
+ >>> list(a)
+ [array([1, 2]), array([3, 4])]
+ >>> a.tolist()
+ [[1, 2], [3, 4]]
+
+ The base case for this recursion is a 0D array:
+
+ >>> a = np.array(1)
+ >>> list(a)
+ Traceback (most recent call last):
+ ...
+ TypeError: iteration over a 0-d array
+ >>> a.tolist()
+ 1
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('tobytes', """
+ a.tobytes(order='C')
+
+ Construct Python bytes containing the raw data bytes in the array.
+
+ Constructs Python bytes showing a copy of the raw contents of
+ data memory. The bytes object is produced in C-order by default.
+ This behavior is controlled by the ``order`` parameter.
+
+ Parameters
+ ----------
+ order : {'C', 'F', 'A'}, optional
+ Controls the memory layout of the bytes object. 'C' means C-order,
+ 'F' means F-order, 'A' (short for *Any*) means 'F' if `a` is
+ Fortran contiguous, 'C' otherwise. Default is 'C'.
+
+ Returns
+ -------
+ s : bytes
+ Python bytes exhibiting a copy of `a`'s raw data.
+
+ See also
+ --------
+ frombuffer
+ Inverse of this operation, construct a 1-dimensional array from Python
+ bytes.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.array([[0, 1], [2, 3]], dtype='>> x.tobytes()
+ b'\\x00\\x00\\x01\\x00\\x02\\x00\\x03\\x00'
+ >>> x.tobytes('C') == x.tobytes()
+ True
+ >>> x.tobytes('F')
+ b'\\x00\\x00\\x02\\x00\\x01\\x00\\x03\\x00'
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('tostring', r"""
+ a.tostring(order='C')
+
+ A compatibility alias for `~ndarray.tobytes`, with exactly the same
+ behavior.
+
+ Despite its name, it returns :class:`bytes` not :class:`str`\ s.
+
+ .. deprecated:: 1.19.0
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('trace',
+ """
+ a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)
+
+ Return the sum along diagonals of the array.
+
+ Refer to `numpy.trace` for full documentation.
+
+ See Also
+ --------
+ numpy.trace : equivalent function
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('transpose',
+ """
+ a.transpose(*axes)
+
+ Returns a view of the array with axes transposed.
+
+ Refer to `numpy.transpose` for full documentation.
+
+ Parameters
+ ----------
+ axes : None, tuple of ints, or `n` ints
+
+ * None or no argument: reverses the order of the axes.
+
+ * tuple of ints: `i` in the `j`-th place in the tuple means that the
+ array's `i`-th axis becomes the transposed array's `j`-th axis.
+
+ * `n` ints: same as an n-tuple of the same ints (this form is
+ intended simply as a "convenience" alternative to the tuple form).
+
+ Returns
+ -------
+ p : ndarray
+ View of the array with its axes suitably permuted.
+
+ See Also
+ --------
+ transpose : Equivalent function.
+ ndarray.T : Array property returning the array transposed.
+ ndarray.reshape : Give a new shape to an array without changing its data.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[1, 2], [3, 4]])
+ >>> a
+ array([[1, 2],
+ [3, 4]])
+ >>> a.transpose()
+ array([[1, 3],
+ [2, 4]])
+ >>> a.transpose((1, 0))
+ array([[1, 3],
+ [2, 4]])
+ >>> a.transpose(1, 0)
+ array([[1, 3],
+ [2, 4]])
+
+ >>> a = np.array([1, 2, 3, 4])
+ >>> a
+ array([1, 2, 3, 4])
+ >>> a.transpose()
+ array([1, 2, 3, 4])
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('var',
+ """
+ a.var(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True)
+
+ Returns the variance of the array elements, along given axis.
+
+ Refer to `numpy.var` for full documentation.
+
+ See Also
+ --------
+ numpy.var : equivalent function
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('view',
+ """
+ a.view([dtype][, type])
+
+ New view of array with the same data.
+
+ .. note::
+ Passing None for ``dtype`` is different from omitting the parameter,
+ since the former invokes ``dtype(None)`` which is an alias for
+ ``dtype('float64')``.
+
+ Parameters
+ ----------
+ dtype : data-type or ndarray sub-class, optional
+ Data-type descriptor of the returned view, e.g., float32 or int16.
+ Omitting it results in the view having the same data-type as `a`.
+ This argument can also be specified as an ndarray sub-class, which
+ then specifies the type of the returned object (this is equivalent to
+ setting the ``type`` parameter).
+ type : Python type, optional
+ Type of the returned view, e.g., ndarray or matrix. Again, omission
+ of the parameter results in type preservation.
+
+ Notes
+ -----
+ ``a.view()`` is used two different ways:
+
+ ``a.view(some_dtype)`` or ``a.view(dtype=some_dtype)`` constructs a view
+ of the array's memory with a different data-type. This can cause a
+ reinterpretation of the bytes of memory.
+
+ ``a.view(ndarray_subclass)`` or ``a.view(type=ndarray_subclass)`` just
+ returns an instance of `ndarray_subclass` that looks at the same array
+ (same shape, dtype, etc.) This does not cause a reinterpretation of the
+ memory.
+
+ For ``a.view(some_dtype)``, if ``some_dtype`` has a different number of
+ bytes per entry than the previous dtype (for example, converting a regular
+ array to a structured array), then the last axis of ``a`` must be
+ contiguous. This axis will be resized in the result.
+
+ .. versionchanged:: 1.23.0
+ Only the last axis needs to be contiguous. Previously, the entire array
+ had to be C-contiguous.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.array([(-1, 2)], dtype=[('a', np.int8), ('b', np.int8)])
+
+ Viewing array data using a different type and dtype:
+
+ >>> nonneg = np.dtype([("a", np.uint8), ("b", np.uint8)])
+ >>> y = x.view(dtype=nonneg, type=np.recarray)
+ >>> x["a"]
+ array([-1], dtype=int8)
+ >>> y.a
+ array([255], dtype=uint8)
+
+ Creating a view on a structured array so it can be used in calculations
+
+ >>> x = np.array([(1, 2),(3,4)], dtype=[('a', np.int8), ('b', np.int8)])
+ >>> xv = x.view(dtype=np.int8).reshape(-1,2)
+ >>> xv
+ array([[1, 2],
+ [3, 4]], dtype=int8)
+ >>> xv.mean(0)
+ array([2., 3.])
+
+ Making changes to the view changes the underlying array
+
+ >>> xv[0,1] = 20
+ >>> x
+ array([(1, 20), (3, 4)], dtype=[('a', 'i1'), ('b', 'i1')])
+
+ Using a view to convert an array to a recarray:
+
+ >>> z = x.view(np.recarray)
+ >>> z.a
+ array([1, 3], dtype=int8)
+
+ Views share data:
+
+ >>> x[0] = (9, 10)
+ >>> z[0]
+ np.record((9, 10), dtype=[('a', 'i1'), ('b', 'i1')])
+
+ Views that change the dtype size (bytes per entry) should normally be
+ avoided on arrays defined by slices, transposes, fortran-ordering, etc.:
+
+ >>> x = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int16)
+ >>> y = x[:, ::2]
+ >>> y
+ array([[1, 3],
+ [4, 6]], dtype=int16)
+ >>> y.view(dtype=[('width', np.int16), ('length', np.int16)])
+ Traceback (most recent call last):
+ ...
+ ValueError: To change to a dtype of a different size, the last axis must be contiguous
+ >>> z = y.copy()
+ >>> z.view(dtype=[('width', np.int16), ('length', np.int16)])
+ array([[(1, 3)],
+ [(4, 6)]], dtype=[('width', '>> x = np.arange(2 * 3 * 4, dtype=np.int8).reshape(2, 3, 4)
+ >>> x.transpose(1, 0, 2).view(np.int16)
+ array([[[ 256, 770],
+ [3340, 3854]],
+
+ [[1284, 1798],
+ [4368, 4882]],
+
+ [[2312, 2826],
+ [5396, 5910]]], dtype=int16)
+
+ """))
+
+
+##############################################################################
+#
+# umath functions
+#
+##############################################################################
+
+add_newdoc('numpy._core.umath', 'frompyfunc',
+ """
+ frompyfunc(func, /, nin, nout, *[, identity])
+
+ Takes an arbitrary Python function and returns a NumPy ufunc.
+
+ Can be used, for example, to add broadcasting to a built-in Python
+ function (see Examples section).
+
+ Parameters
+ ----------
+ func : Python function object
+ An arbitrary Python function.
+ nin : int
+ The number of input arguments.
+ nout : int
+ The number of objects returned by `func`.
+ identity : object, optional
+ The value to use for the `~numpy.ufunc.identity` attribute of the resulting
+ object. If specified, this is equivalent to setting the underlying
+ C ``identity`` field to ``PyUFunc_IdentityValue``.
+ If omitted, the identity is set to ``PyUFunc_None``. Note that this is
+ _not_ equivalent to setting the identity to ``None``, which implies the
+ operation is reorderable.
+
+ Returns
+ -------
+ out : ufunc
+ Returns a NumPy universal function (``ufunc``) object.
+
+ See Also
+ --------
+ vectorize : Evaluates pyfunc over input arrays using broadcasting rules of numpy.
+
+ Notes
+ -----
+ The returned ufunc always returns PyObject arrays.
+
+ Examples
+ --------
+ Use frompyfunc to add broadcasting to the Python function ``oct``:
+
+ >>> import numpy as np
+ >>> oct_array = np.frompyfunc(oct, 1, 1)
+ >>> oct_array(np.array((10, 30, 100)))
+ array(['0o12', '0o36', '0o144'], dtype=object)
+ >>> np.array((oct(10), oct(30), oct(100))) # for comparison
+ array(['0o12', '0o36', '0o144'], dtype='doc is NULL.)
+
+ Parameters
+ ----------
+ ufunc : numpy.ufunc
+ A ufunc whose current doc is NULL.
+ new_docstring : string
+ The new docstring for the ufunc.
+
+ Notes
+ -----
+ This method allocates memory for new_docstring on
+ the heap. Technically this creates a memory leak, since this
+ memory will not be reclaimed until the end of the program
+ even if the ufunc itself is removed. However this will only
+ be a problem if the user is repeatedly creating ufuncs with
+ no documentation, adding documentation via add_newdoc_ufunc,
+ and then throwing away the ufunc.
+ """)
+
+add_newdoc('numpy._core.multiarray', 'get_handler_name',
+ """
+ get_handler_name(a: ndarray) -> str,None
+
+ Return the name of the memory handler used by `a`. If not provided, return
+ the name of the memory handler that will be used to allocate data for the
+ next `ndarray` in this context. May return None if `a` does not own its
+ memory, in which case you can traverse ``a.base`` for a memory handler.
+ """)
+
+add_newdoc('numpy._core.multiarray', 'get_handler_version',
+ """
+ get_handler_version(a: ndarray) -> int,None
+
+ Return the version of the memory handler used by `a`. If not provided,
+ return the version of the memory handler that will be used to allocate data
+ for the next `ndarray` in this context. May return None if `a` does not own
+ its memory, in which case you can traverse ``a.base`` for a memory handler.
+ """)
+
+add_newdoc('numpy._core._multiarray_umath', '_array_converter',
+ """
+ _array_converter(*array_likes)
+
+ Helper to convert one or more objects to arrays. Integrates machinery
+ to deal with the ``result_type`` and ``__array_wrap__``.
+
+ The reason for this is that e.g. ``result_type`` needs to convert to arrays
+ to find the ``dtype``. But converting to an array before calling
+ ``result_type`` would incorrectly "forget" whether it was a Python int,
+ float, or complex.
+ """)
+
+add_newdoc(
+ 'numpy._core._multiarray_umath', '_array_converter', ('scalar_input',
+ """
+ A tuple which indicates for each input whether it was a scalar that
+ was coerced to a 0-D array (and was not already an array or something
+ converted via a protocol like ``__array__()``).
+ """))
+
+add_newdoc('numpy._core._multiarray_umath', '_array_converter', ('as_arrays',
+ """
+ as_arrays(/, subok=True, pyscalars="convert_if_no_array")
+
+ Return the inputs as arrays or scalars.
+
+ Parameters
+ ----------
+ subok : True or False, optional
+ Whether array subclasses are preserved.
+ pyscalars : {"convert", "preserve", "convert_if_no_array"}, optional
+ To allow NEP 50 weak promotion later, it may be desirable to preserve
+ Python scalars. As default, these are preserved unless all inputs
+ are Python scalars. "convert" enforces an array return.
+ """))
+
+add_newdoc('numpy._core._multiarray_umath', '_array_converter', ('result_type',
+ """result_type(/, extra_dtype=None, ensure_inexact=False)
+
+ Find the ``result_type`` just as ``np.result_type`` would, but taking
+ into account that the original inputs (before converting to an array) may
+ have been Python scalars with weak promotion.
+
+ Parameters
+ ----------
+ extra_dtype : dtype instance or class
+ An additional DType or dtype instance to promote (e.g. could be used
+ to ensure the result precision is at least float32).
+ ensure_inexact : True or False
+ When ``True``, ensures a floating point (or complex) result replacing
+ the ``arr * 1.`` or ``result_type(..., 0.0)`` pattern.
+ """))
+
+add_newdoc('numpy._core._multiarray_umath', '_array_converter', ('wrap',
+ """
+ wrap(arr, /, to_scalar=None)
+
+ Call ``__array_wrap__`` on ``arr`` if ``arr`` is not the same subclass
+ as the input the ``__array_wrap__`` method was retrieved from.
+
+ Parameters
+ ----------
+ arr : ndarray
+ The object to be wrapped. Normally an ndarray or subclass,
+ although for backward compatibility NumPy scalars are also accepted
+ (these will be converted to a NumPy array before being passed on to
+ the ``__array_wrap__`` method).
+ to_scalar : {True, False, None}, optional
+ When ``True`` will convert a 0-d array to a scalar via ``result[()]``
+ (with a fast-path for non-subclasses). If ``False`` the result should
+ be an array-like (as ``__array_wrap__`` is free to return a non-array).
+ By default (``None``), a scalar is returned if all inputs were scalar.
+ """))
+
+
+add_newdoc('numpy._core.multiarray', '_get_madvise_hugepage',
+ """
+ _get_madvise_hugepage() -> bool
+
+ Get use of ``madvise (2)`` MADV_HUGEPAGE support when
+ allocating the array data. Returns the currently set value.
+ See `global_state` for more information.
+ """)
+
+add_newdoc('numpy._core.multiarray', '_set_madvise_hugepage',
+ """
+ _set_madvise_hugepage(enabled: bool) -> bool
+
+ Set or unset use of ``madvise (2)`` MADV_HUGEPAGE support when
+ allocating the array data. Returns the previously set value.
+ See `global_state` for more information.
+ """)
+
+
+##############################################################################
+#
+# Documentation for ufunc attributes and methods
+#
+##############################################################################
+
+
+##############################################################################
+#
+# ufunc object
+#
+##############################################################################
+
+add_newdoc('numpy._core', 'ufunc',
+ """
+ Functions that operate element by element on whole arrays.
+
+ To see the documentation for a specific ufunc, use `info`. For
+ example, ``np.info(np.sin)``. Because ufuncs are written in C
+ (for speed) and linked into Python with NumPy's ufunc facility,
+ Python's help() function finds this page whenever help() is called
+ on a ufunc.
+
+ A detailed explanation of ufuncs can be found in the docs for :ref:`ufuncs`.
+
+ **Calling ufuncs:** ``op(*x[, out], where=True, **kwargs)``
+
+ Apply `op` to the arguments `*x` elementwise, broadcasting the arguments.
+
+ The broadcasting rules are:
+
+ * Dimensions of length 1 may be prepended to either array.
+ * Arrays may be repeated along dimensions of length 1.
+
+ Parameters
+ ----------
+ *x : array_like
+ Input arrays.
+ out : ndarray, None, or tuple of ndarray and None, optional
+ Alternate array object(s) in which to put the result; if provided, it
+ must have a shape that the inputs broadcast to. A tuple of arrays
+ (possible only as a keyword argument) must have length equal to the
+ number of outputs; use None for uninitialized outputs to be
+ allocated by the ufunc.
+ where : array_like, optional
+ This condition is broadcast over the input. At locations where the
+ condition is True, the `out` array will be set to the ufunc result.
+ Elsewhere, the `out` array will retain its original value.
+ Note that if an uninitialized `out` array is created via the default
+ ``out=None``, locations within it where the condition is False will
+ remain uninitialized.
+ **kwargs
+ For other keyword-only arguments, see the :ref:`ufunc docs `.
+
+ Returns
+ -------
+ r : ndarray or tuple of ndarray
+ `r` will have the shape that the arrays in `x` broadcast to; if `out` is
+ provided, it will be returned. If not, `r` will be allocated and
+ may contain uninitialized values. If the function has more than one
+ output, then the result will be a tuple of arrays.
+
+ """)
+
+
+##############################################################################
+#
+# ufunc attributes
+#
+##############################################################################
+
+add_newdoc('numpy._core', 'ufunc', ('identity',
+ """
+ The identity value.
+
+ Data attribute containing the identity element for the ufunc,
+ if it has one. If it does not, the attribute value is None.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.add.identity
+ 0
+ >>> np.multiply.identity
+ 1
+ >>> np.power.identity
+ 1
+ >>> print(np.exp.identity)
+ None
+ """))
+
+add_newdoc('numpy._core', 'ufunc', ('nargs',
+ """
+ The number of arguments.
+
+ Data attribute containing the number of arguments the ufunc takes, including
+ optional ones.
+
+ Notes
+ -----
+ Typically this value will be one more than what you might expect
+ because all ufuncs take the optional "out" argument.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.add.nargs
+ 3
+ >>> np.multiply.nargs
+ 3
+ >>> np.power.nargs
+ 3
+ >>> np.exp.nargs
+ 2
+ """))
+
+add_newdoc('numpy._core', 'ufunc', ('nin',
+ """
+ The number of inputs.
+
+ Data attribute containing the number of arguments the ufunc treats as input.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.add.nin
+ 2
+ >>> np.multiply.nin
+ 2
+ >>> np.power.nin
+ 2
+ >>> np.exp.nin
+ 1
+ """))
+
+add_newdoc('numpy._core', 'ufunc', ('nout',
+ """
+ The number of outputs.
+
+ Data attribute containing the number of arguments the ufunc treats as output.
+
+ Notes
+ -----
+ Since all ufuncs can take output arguments, this will always be at least 1.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.add.nout
+ 1
+ >>> np.multiply.nout
+ 1
+ >>> np.power.nout
+ 1
+ >>> np.exp.nout
+ 1
+
+ """))
+
+add_newdoc('numpy._core', 'ufunc', ('ntypes',
+ """
+ The number of types.
+
+ The number of numerical NumPy types - of which there are 18 total - on which
+ the ufunc can operate.
+
+ See Also
+ --------
+ numpy.ufunc.types
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.add.ntypes
+ 18
+ >>> np.multiply.ntypes
+ 18
+ >>> np.power.ntypes
+ 17
+ >>> np.exp.ntypes
+ 7
+ >>> np.remainder.ntypes
+ 14
+
+ """))
+
+add_newdoc('numpy._core', 'ufunc', ('types',
+ """
+ Returns a list with types grouped input->output.
+
+ Data attribute listing the data-type "Domain-Range" groupings the ufunc can
+ deliver. The data-types are given using the character codes.
+
+ See Also
+ --------
+ numpy.ufunc.ntypes
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.add.types
+ ['??->?', 'bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l',
+ 'LL->L', 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D',
+ 'GG->G', 'OO->O']
+
+ >>> np.multiply.types
+ ['??->?', 'bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l',
+ 'LL->L', 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D',
+ 'GG->G', 'OO->O']
+
+ >>> np.power.types
+ ['bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 'LL->L',
+ 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D', 'GG->G',
+ 'OO->O']
+
+ >>> np.exp.types
+ ['f->f', 'd->d', 'g->g', 'F->F', 'D->D', 'G->G', 'O->O']
+
+ >>> np.remainder.types
+ ['bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 'LL->L',
+ 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'OO->O']
+
+ """))
+
+add_newdoc('numpy._core', 'ufunc', ('signature',
+ """
+ Definition of the core elements a generalized ufunc operates on.
+
+ The signature determines how the dimensions of each input/output array
+ are split into core and loop dimensions:
+
+ 1. Each dimension in the signature is matched to a dimension of the
+ corresponding passed-in array, starting from the end of the shape tuple.
+ 2. Core dimensions assigned to the same label in the signature must have
+ exactly matching sizes, no broadcasting is performed.
+ 3. The core dimensions are removed from all inputs and the remaining
+ dimensions are broadcast together, defining the loop dimensions.
+
+ Notes
+ -----
+ Generalized ufuncs are used internally in many linalg functions, and in
+ the testing suite; the examples below are taken from these.
+ For ufuncs that operate on scalars, the signature is None, which is
+ equivalent to '()' for every argument.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.linalg._umath_linalg.det.signature
+ '(m,m)->()'
+ >>> np.matmul.signature
+ '(n?,k),(k,m?)->(n?,m?)'
+ >>> np.add.signature is None
+ True # equivalent to '(),()->()'
+ """))
+
+##############################################################################
+#
+# ufunc methods
+#
+##############################################################################
+
+add_newdoc('numpy._core', 'ufunc', ('reduce',
+ """
+ reduce(array, axis=0, dtype=None, out=None, keepdims=False, initial=, where=True)
+
+ Reduces `array`'s dimension by one, by applying ufunc along one axis.
+
+ Let :math:`array.shape = (N_0, ..., N_i, ..., N_{M-1})`. Then
+ :math:`ufunc.reduce(array, axis=i)[k_0, ..,k_{i-1}, k_{i+1}, .., k_{M-1}]` =
+ the result of iterating `j` over :math:`range(N_i)`, cumulatively applying
+ ufunc to each :math:`array[k_0, ..,k_{i-1}, j, k_{i+1}, .., k_{M-1}]`.
+ For a one-dimensional array, reduce produces results equivalent to:
+ ::
+
+ r = op.identity # op = ufunc
+ for i in range(len(A)):
+ r = op(r, A[i])
+ return r
+
+ For example, add.reduce() is equivalent to sum().
+
+ Parameters
+ ----------
+ array : array_like
+ The array to act on.
+ axis : None or int or tuple of ints, optional
+ Axis or axes along which a reduction is performed.
+ The default (`axis` = 0) is perform a reduction over the first
+ dimension of the input array. `axis` may be negative, in
+ which case it counts from the last to the first axis.
+
+ If this is None, a reduction is performed over all the axes.
+ If this is a tuple of ints, a reduction is performed on multiple
+ axes, instead of a single axis or all the axes as before.
+
+ For operations which are either not commutative or not associative,
+ doing a reduction over multiple axes is not well-defined. The
+ ufuncs do not currently raise an exception in this case, but will
+ likely do so in the future.
+ dtype : data-type code, optional
+ The data type used to perform the operation. Defaults to that of
+ ``out`` if given, and the data type of ``array`` otherwise (though
+ upcast to conserve precision for some cases, such as
+ ``numpy.add.reduce`` for integer or boolean input).
+ out : ndarray, None, or tuple of ndarray and None, optional
+ A location into which the result is stored. If not provided or None,
+ a freshly-allocated array is returned. For consistency with
+ ``ufunc.__call__``, if given as a keyword, this may be wrapped in a
+ 1-element tuple.
+ keepdims : bool, optional
+ If this is set to True, the axes which are reduced are left
+ in the result as dimensions with size one. With this option,
+ the result will broadcast correctly against the original `array`.
+ initial : scalar, optional
+ The value with which to start the reduction.
+ If the ufunc has no identity or the dtype is object, this defaults
+ to None - otherwise it defaults to ufunc.identity.
+ If ``None`` is given, the first element of the reduction is used,
+ and an error is thrown if the reduction is empty.
+ where : array_like of bool, optional
+ A boolean array which is broadcasted to match the dimensions
+ of `array`, and selects elements to include in the reduction. Note
+ that for ufuncs like ``minimum`` that do not have an identity
+ defined, one has to pass in also ``initial``.
+
+ Returns
+ -------
+ r : ndarray
+ The reduced array. If `out` was supplied, `r` is a reference to it.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.multiply.reduce([2,3,5])
+ 30
+
+ A multi-dimensional array example:
+
+ >>> X = np.arange(8).reshape((2,2,2))
+ >>> X
+ array([[[0, 1],
+ [2, 3]],
+ [[4, 5],
+ [6, 7]]])
+ >>> np.add.reduce(X, 0)
+ array([[ 4, 6],
+ [ 8, 10]])
+ >>> np.add.reduce(X) # confirm: default axis value is 0
+ array([[ 4, 6],
+ [ 8, 10]])
+ >>> np.add.reduce(X, 1)
+ array([[ 2, 4],
+ [10, 12]])
+ >>> np.add.reduce(X, 2)
+ array([[ 1, 5],
+ [ 9, 13]])
+
+ You can use the ``initial`` keyword argument to initialize the reduction
+ with a different value, and ``where`` to select specific elements to include:
+
+ >>> np.add.reduce([10], initial=5)
+ 15
+ >>> np.add.reduce(np.ones((2, 2, 2)), axis=(0, 2), initial=10)
+ array([14., 14.])
+ >>> a = np.array([10., np.nan, 10])
+ >>> np.add.reduce(a, where=~np.isnan(a))
+ 20.0
+
+ Allows reductions of empty arrays where they would normally fail, i.e.
+ for ufuncs without an identity.
+
+ >>> np.minimum.reduce([], initial=np.inf)
+ inf
+ >>> np.minimum.reduce([[1., 2.], [3., 4.]], initial=10., where=[True, False])
+ array([ 1., 10.])
+ >>> np.minimum.reduce([])
+ Traceback (most recent call last):
+ ...
+ ValueError: zero-size array to reduction operation minimum which has no identity
+ """))
+
+add_newdoc('numpy._core', 'ufunc', ('accumulate',
+ """
+ accumulate(array, axis=0, dtype=None, out=None)
+
+ Accumulate the result of applying the operator to all elements.
+
+ For a one-dimensional array, accumulate produces results equivalent to::
+
+ r = np.empty(len(A))
+ t = op.identity # op = the ufunc being applied to A's elements
+ for i in range(len(A)):
+ t = op(t, A[i])
+ r[i] = t
+ return r
+
+ For example, add.accumulate() is equivalent to np.cumsum().
+
+ For a multi-dimensional array, accumulate is applied along only one
+ axis (axis zero by default; see Examples below) so repeated use is
+ necessary if one wants to accumulate over multiple axes.
+
+ Parameters
+ ----------
+ array : array_like
+ The array to act on.
+ axis : int, optional
+ The axis along which to apply the accumulation; default is zero.
+ dtype : data-type code, optional
+ The data-type used to represent the intermediate results. Defaults
+ to the data-type of the output array if such is provided, or the
+ data-type of the input array if no output array is provided.
+ out : ndarray, None, or tuple of ndarray and None, optional
+ A location into which the result is stored. If not provided or None,
+ a freshly-allocated array is returned. For consistency with
+ ``ufunc.__call__``, if given as a keyword, this may be wrapped in a
+ 1-element tuple.
+
+ Returns
+ -------
+ r : ndarray
+ The accumulated values. If `out` was supplied, `r` is a reference to
+ `out`.
+
+ Examples
+ --------
+ 1-D array examples:
+
+ >>> import numpy as np
+ >>> np.add.accumulate([2, 3, 5])
+ array([ 2, 5, 10])
+ >>> np.multiply.accumulate([2, 3, 5])
+ array([ 2, 6, 30])
+
+ 2-D array examples:
+
+ >>> I = np.eye(2)
+ >>> I
+ array([[1., 0.],
+ [0., 1.]])
+
+ Accumulate along axis 0 (rows), down columns:
+
+ >>> np.add.accumulate(I, 0)
+ array([[1., 0.],
+ [1., 1.]])
+ >>> np.add.accumulate(I) # no axis specified = axis zero
+ array([[1., 0.],
+ [1., 1.]])
+
+ Accumulate along axis 1 (columns), through rows:
+
+ >>> np.add.accumulate(I, 1)
+ array([[1., 1.],
+ [0., 1.]])
+
+ """))
+
+add_newdoc('numpy._core', 'ufunc', ('reduceat',
+ """
+ reduceat(array, indices, axis=0, dtype=None, out=None)
+
+ Performs a (local) reduce with specified slices over a single axis.
+
+ For i in ``range(len(indices))``, `reduceat` computes
+ ``ufunc.reduce(array[indices[i]:indices[i+1]])``, which becomes the i-th
+ generalized "row" parallel to `axis` in the final result (i.e., in a
+ 2-D array, for example, if `axis = 0`, it becomes the i-th row, but if
+ `axis = 1`, it becomes the i-th column). There are three exceptions to this:
+
+ * when ``i = len(indices) - 1`` (so for the last index),
+ ``indices[i+1] = array.shape[axis]``.
+ * if ``indices[i] >= indices[i + 1]``, the i-th generalized "row" is
+ simply ``array[indices[i]]``.
+ * if ``indices[i] >= len(array)`` or ``indices[i] < 0``, an error is raised.
+
+ The shape of the output depends on the size of `indices`, and may be
+ larger than `array` (this happens if ``len(indices) > array.shape[axis]``).
+
+ Parameters
+ ----------
+ array : array_like
+ The array to act on.
+ indices : array_like
+ Paired indices, comma separated (not colon), specifying slices to
+ reduce.
+ axis : int, optional
+ The axis along which to apply the reduceat.
+ dtype : data-type code, optional
+ The data type used to perform the operation. Defaults to that of
+ ``out`` if given, and the data type of ``array`` otherwise (though
+ upcast to conserve precision for some cases, such as
+ ``numpy.add.reduce`` for integer or boolean input).
+ out : ndarray, None, or tuple of ndarray and None, optional
+ A location into which the result is stored. If not provided or None,
+ a freshly-allocated array is returned. For consistency with
+ ``ufunc.__call__``, if given as a keyword, this may be wrapped in a
+ 1-element tuple.
+
+ Returns
+ -------
+ r : ndarray
+ The reduced values. If `out` was supplied, `r` is a reference to
+ `out`.
+
+ Notes
+ -----
+ A descriptive example:
+
+ If `array` is 1-D, the function `ufunc.accumulate(array)` is the same as
+ ``ufunc.reduceat(array, indices)[::2]`` where `indices` is
+ ``range(len(array) - 1)`` with a zero placed
+ in every other element:
+ ``indices = zeros(2 * len(array) - 1)``,
+ ``indices[1::2] = range(1, len(array))``.
+
+ Don't be fooled by this attribute's name: `reduceat(array)` is not
+ necessarily smaller than `array`.
+
+ Examples
+ --------
+ To take the running sum of four successive values:
+
+ >>> import numpy as np
+ >>> np.add.reduceat(np.arange(8),[0,4, 1,5, 2,6, 3,7])[::2]
+ array([ 6, 10, 14, 18])
+
+ A 2-D example:
+
+ >>> x = np.linspace(0, 15, 16).reshape(4,4)
+ >>> x
+ array([[ 0., 1., 2., 3.],
+ [ 4., 5., 6., 7.],
+ [ 8., 9., 10., 11.],
+ [12., 13., 14., 15.]])
+
+ ::
+
+ # reduce such that the result has the following five rows:
+ # [row1 + row2 + row3]
+ # [row4]
+ # [row2]
+ # [row3]
+ # [row1 + row2 + row3 + row4]
+
+ >>> np.add.reduceat(x, [0, 3, 1, 2, 0])
+ array([[12., 15., 18., 21.],
+ [12., 13., 14., 15.],
+ [ 4., 5., 6., 7.],
+ [ 8., 9., 10., 11.],
+ [24., 28., 32., 36.]])
+
+ ::
+
+ # reduce such that result has the following two columns:
+ # [col1 * col2 * col3, col4]
+
+ >>> np.multiply.reduceat(x, [0, 3], 1)
+ array([[ 0., 3.],
+ [ 120., 7.],
+ [ 720., 11.],
+ [2184., 15.]])
+
+ """))
+
+add_newdoc('numpy._core', 'ufunc', ('outer',
+ r"""
+ outer(A, B, /, **kwargs)
+
+ Apply the ufunc `op` to all pairs (a, b) with a in `A` and b in `B`.
+
+ Let ``M = A.ndim``, ``N = B.ndim``. Then the result, `C`, of
+ ``op.outer(A, B)`` is an array of dimension M + N such that:
+
+ .. math:: C[i_0, ..., i_{M-1}, j_0, ..., j_{N-1}] =
+ op(A[i_0, ..., i_{M-1}], B[j_0, ..., j_{N-1}])
+
+ For `A` and `B` one-dimensional, this is equivalent to::
+
+ r = empty(len(A),len(B))
+ for i in range(len(A)):
+ for j in range(len(B)):
+ r[i,j] = op(A[i], B[j]) # op = ufunc in question
+
+ Parameters
+ ----------
+ A : array_like
+ First array
+ B : array_like
+ Second array
+ kwargs : any
+ Arguments to pass on to the ufunc. Typically `dtype` or `out`.
+ See `ufunc` for a comprehensive overview of all available arguments.
+
+ Returns
+ -------
+ r : ndarray
+ Output array
+
+ See Also
+ --------
+ numpy.outer : A less powerful version of ``np.multiply.outer``
+ that `ravel`\ s all inputs to 1D. This exists
+ primarily for compatibility with old code.
+
+ tensordot : ``np.tensordot(a, b, axes=((), ()))`` and
+ ``np.multiply.outer(a, b)`` behave same for all
+ dimensions of a and b.
+
+ Examples
+ --------
+ >>> np.multiply.outer([1, 2, 3], [4, 5, 6])
+ array([[ 4, 5, 6],
+ [ 8, 10, 12],
+ [12, 15, 18]])
+
+ A multi-dimensional example:
+
+ >>> A = np.array([[1, 2, 3], [4, 5, 6]])
+ >>> A.shape
+ (2, 3)
+ >>> B = np.array([[1, 2, 3, 4]])
+ >>> B.shape
+ (1, 4)
+ >>> C = np.multiply.outer(A, B)
+ >>> C.shape; C
+ (2, 3, 1, 4)
+ array([[[[ 1, 2, 3, 4]],
+ [[ 2, 4, 6, 8]],
+ [[ 3, 6, 9, 12]]],
+ [[[ 4, 8, 12, 16]],
+ [[ 5, 10, 15, 20]],
+ [[ 6, 12, 18, 24]]]])
+
+ """))
+
+add_newdoc('numpy._core', 'ufunc', ('at',
+ """
+ at(a, indices, b=None, /)
+
+ Performs unbuffered in place operation on operand 'a' for elements
+ specified by 'indices'. For addition ufunc, this method is equivalent to
+ ``a[indices] += b``, except that results are accumulated for elements that
+ are indexed more than once. For example, ``a[[0,0]] += 1`` will only
+ increment the first element once because of buffering, whereas
+ ``add.at(a, [0,0], 1)`` will increment the first element twice.
+
+ Parameters
+ ----------
+ a : array_like
+ The array to perform in place operation on.
+ indices : array_like or tuple
+ Array like index object or slice object for indexing into first
+ operand. If first operand has multiple dimensions, indices can be a
+ tuple of array like index objects or slice objects.
+ b : array_like
+ Second operand for ufuncs requiring two operands. Operand must be
+ broadcastable over first operand after indexing or slicing.
+
+ Examples
+ --------
+ Set items 0 and 1 to their negative values:
+
+ >>> import numpy as np
+ >>> a = np.array([1, 2, 3, 4])
+ >>> np.negative.at(a, [0, 1])
+ >>> a
+ array([-1, -2, 3, 4])
+
+ Increment items 0 and 1, and increment item 2 twice:
+
+ >>> a = np.array([1, 2, 3, 4])
+ >>> np.add.at(a, [0, 1, 2, 2], 1)
+ >>> a
+ array([2, 3, 5, 4])
+
+ Add items 0 and 1 in first array to second array,
+ and store results in first array:
+
+ >>> a = np.array([1, 2, 3, 4])
+ >>> b = np.array([1, 2])
+ >>> np.add.at(a, [0, 1], b)
+ >>> a
+ array([2, 4, 3, 4])
+
+ """))
+
+add_newdoc('numpy._core', 'ufunc', ('resolve_dtypes',
+ """
+ resolve_dtypes(dtypes, *, signature=None, casting=None, reduction=False)
+
+ Find the dtypes NumPy will use for the operation. Both input and
+ output dtypes are returned and may differ from those provided.
+
+ .. note::
+
+ This function always applies NEP 50 rules since it is not provided
+ any actual values. The Python types ``int``, ``float``, and
+ ``complex`` thus behave weak and should be passed for "untyped"
+ Python input.
+
+ Parameters
+ ----------
+ dtypes : tuple of dtypes, None, or literal int, float, complex
+ The input dtypes for each operand. Output operands can be
+ None, indicating that the dtype must be found.
+ signature : tuple of DTypes or None, optional
+ If given, enforces exact DType (classes) of the specific operand.
+ The ufunc ``dtype`` argument is equivalent to passing a tuple with
+ only output dtypes set.
+ casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
+ The casting mode when casting is necessary. This is identical to
+ the ufunc call casting modes.
+ reduction : boolean
+ If given, the resolution assumes a reduce operation is happening
+ which slightly changes the promotion and type resolution rules.
+ `dtypes` is usually something like ``(None, np.dtype("i2"), None)``
+ for reductions (first input is also the output).
+
+ .. note::
+
+ The default casting mode is "same_kind", however, as of
+ NumPy 1.24, NumPy uses "unsafe" for reductions.
+
+ Returns
+ -------
+ dtypes : tuple of dtypes
+ The dtypes which NumPy would use for the calculation. Note that
+ dtypes may not match the passed in ones (casting is necessary).
+
+
+ Examples
+ --------
+ This API requires passing dtypes, define them for convenience:
+
+ >>> import numpy as np
+ >>> int32 = np.dtype("int32")
+ >>> float32 = np.dtype("float32")
+
+ The typical ufunc call does not pass an output dtype. `numpy.add` has two
+ inputs and one output, so leave the output as ``None`` (not provided):
+
+ >>> np.add.resolve_dtypes((int32, float32, None))
+ (dtype('float64'), dtype('float64'), dtype('float64'))
+
+ The loop found uses "float64" for all operands (including the output), the
+ first input would be cast.
+
+ ``resolve_dtypes`` supports "weak" handling for Python scalars by passing
+ ``int``, ``float``, or ``complex``:
+
+ >>> np.add.resolve_dtypes((float32, float, None))
+ (dtype('float32'), dtype('float32'), dtype('float32'))
+
+ Where the Python ``float`` behaves similar to a Python value ``0.0``
+ in a ufunc call. (See :ref:`NEP 50 ` for details.)
+
+ """))
+
+add_newdoc('numpy._core', 'ufunc', ('_resolve_dtypes_and_context',
+ """
+ _resolve_dtypes_and_context(dtypes, *, signature=None, casting=None, reduction=False)
+
+ See `numpy.ufunc.resolve_dtypes` for parameter information. This
+ function is considered *unstable*. You may use it, but the returned
+ information is NumPy version specific and expected to change.
+ Large API/ABI changes are not expected, but a new NumPy version is
+ expected to require updating code using this functionality.
+
+ This function is designed to be used in conjunction with
+ `numpy.ufunc._get_strided_loop`. The calls are split to mirror the C API
+ and allow future improvements.
+
+ Returns
+ -------
+ dtypes : tuple of dtypes
+ call_info :
+ PyCapsule with all necessary information to get access to low level
+ C calls. See `numpy.ufunc._get_strided_loop` for more information.
+
+ """))
+
+add_newdoc('numpy._core', 'ufunc', ('_get_strided_loop',
+ """
+ _get_strided_loop(call_info, /, *, fixed_strides=None)
+
+ This function fills in the ``call_info`` capsule to include all
+ information necessary to call the low-level strided loop from NumPy.
+
+ See notes for more information.
+
+ Parameters
+ ----------
+ call_info : PyCapsule
+ The PyCapsule returned by `numpy.ufunc._resolve_dtypes_and_context`.
+ fixed_strides : tuple of int or None, optional
+ A tuple with fixed byte strides of all input arrays. NumPy may use
+ this information to find specialized loops, so any call must follow
+ the given stride. Use ``None`` to indicate that the stride is not
+ known (or not fixed) for all calls.
+
+ Notes
+ -----
+ Together with `numpy.ufunc._resolve_dtypes_and_context` this function
+ gives low-level access to the NumPy ufunc loops.
+ The first function does general preparation and returns the required
+ information. It returns this as a C capsule with the version specific
+ name ``numpy_1.24_ufunc_call_info``.
+ The NumPy 1.24 ufunc call info capsule has the following layout::
+
+ typedef struct {
+ PyArrayMethod_StridedLoop *strided_loop;
+ PyArrayMethod_Context *context;
+ NpyAuxData *auxdata;
+
+ /* Flag information (expected to change) */
+ npy_bool requires_pyapi; /* GIL is required by loop */
+
+ /* Loop doesn't set FPE flags; if not set check FPE flags */
+ npy_bool no_floatingpoint_errors;
+ } ufunc_call_info;
+
+ Note that the first call only fills in the ``context``. The call to
+ ``_get_strided_loop`` fills in all other data. The main thing to note is
+ that the new-style loops return 0 on success, -1 on failure. They are
+ passed context as new first input and ``auxdata`` as (replaced) last.
+
+ Only the ``strided_loop``signature is considered guaranteed stable
+ for NumPy bug-fix releases. All other API is tied to the experimental
+ API versioning.
+
+ The reason for the split call is that cast information is required to
+ decide what the fixed-strides will be.
+
+ NumPy ties the lifetime of the ``auxdata`` information to the capsule.
+
+ """))
+
+
+
+##############################################################################
+#
+# Documentation for dtype attributes and methods
+#
+##############################################################################
+
+##############################################################################
+#
+# dtype object
+#
+##############################################################################
+
+add_newdoc('numpy._core.multiarray', 'dtype',
+ """
+ dtype(dtype, align=False, copy=False, [metadata])
+
+ Create a data type object.
+
+ A numpy array is homogeneous, and contains elements described by a
+ dtype object. A dtype object can be constructed from different
+ combinations of fundamental numeric types.
+
+ Parameters
+ ----------
+ dtype
+ Object to be converted to a data type object.
+ align : bool, optional
+ Add padding to the fields to match what a C compiler would output
+ for a similar C-struct. Can be ``True`` only if `obj` is a dictionary
+ or a comma-separated string. If a struct dtype is being created,
+ this also sets a sticky alignment flag ``isalignedstruct``.
+ copy : bool, optional
+ Make a new copy of the data-type object. If ``False``, the result
+ may just be a reference to a built-in data-type object.
+ metadata : dict, optional
+ An optional dictionary with dtype metadata.
+
+ See also
+ --------
+ result_type
+
+ Examples
+ --------
+ Using array-scalar type:
+
+ >>> import numpy as np
+ >>> np.dtype(np.int16)
+ dtype('int16')
+
+ Structured type, one field name 'f1', containing int16:
+
+ >>> np.dtype([('f1', np.int16)])
+ dtype([('f1', '>> np.dtype([('f1', [('f1', np.int16)])])
+ dtype([('f1', [('f1', '>> np.dtype([('f1', np.uint64), ('f2', np.int32)])
+ dtype([('f1', '>> np.dtype([('a','f8'),('b','S10')])
+ dtype([('a', '>> np.dtype("i4, (2,3)f8")
+ dtype([('f0', '>> np.dtype([('hello',(np.int64,3)),('world',np.void,10)])
+ dtype([('hello', '>> np.dtype((np.int16, {'x':(np.int8,0), 'y':(np.int8,1)}))
+ dtype((numpy.int16, [('x', 'i1'), ('y', 'i1')]))
+
+ Using dictionaries. Two fields named 'gender' and 'age':
+
+ >>> np.dtype({'names':['gender','age'], 'formats':['S1',np.uint8]})
+ dtype([('gender', 'S1'), ('age', 'u1')])
+
+ Offsets in bytes, here 0 and 25:
+
+ >>> np.dtype({'surname':('S25',0),'age':(np.uint8,25)})
+ dtype([('surname', 'S25'), ('age', 'u1')])
+
+ """)
+
+##############################################################################
+#
+# dtype attributes
+#
+##############################################################################
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('alignment',
+ """
+ The required alignment (bytes) of this data-type according to the compiler.
+
+ More information is available in the C-API section of the manual.
+
+ Examples
+ --------
+
+ >>> import numpy as np
+ >>> x = np.dtype('i4')
+ >>> x.alignment
+ 4
+
+ >>> x = np.dtype(float)
+ >>> x.alignment
+ 8
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('byteorder',
+ """
+ A character indicating the byte-order of this data-type object.
+
+ One of:
+
+ === ==============
+ '=' native
+ '<' little-endian
+ '>' big-endian
+ '|' not applicable
+ === ==============
+
+ All built-in data-type objects have byteorder either '=' or '|'.
+
+ Examples
+ --------
+
+ >>> import numpy as np
+ >>> dt = np.dtype('i2')
+ >>> dt.byteorder
+ '='
+ >>> # endian is not relevant for 8 bit numbers
+ >>> np.dtype('i1').byteorder
+ '|'
+ >>> # or ASCII strings
+ >>> np.dtype('S2').byteorder
+ '|'
+ >>> # Even if specific code is given, and it is native
+ >>> # '=' is the byteorder
+ >>> import sys
+ >>> sys_is_le = sys.byteorder == 'little'
+ >>> native_code = '<' if sys_is_le else '>'
+ >>> swapped_code = '>' if sys_is_le else '<'
+ >>> dt = np.dtype(native_code + 'i2')
+ >>> dt.byteorder
+ '='
+ >>> # Swapped code shows up as itself
+ >>> dt = np.dtype(swapped_code + 'i2')
+ >>> dt.byteorder == swapped_code
+ True
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('char',
+ """A unique character code for each of the 21 different built-in types.
+
+ Examples
+ --------
+
+ >>> import numpy as np
+ >>> x = np.dtype(float)
+ >>> x.char
+ 'd'
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('descr',
+ """
+ `__array_interface__` description of the data-type.
+
+ The format is that required by the 'descr' key in the
+ `__array_interface__` attribute.
+
+ Warning: This attribute exists specifically for `__array_interface__`,
+ and passing it directly to `numpy.dtype` will not accurately reconstruct
+ some dtypes (e.g., scalar and subarray dtypes).
+
+ Examples
+ --------
+
+ >>> import numpy as np
+ >>> x = np.dtype(float)
+ >>> x.descr
+ [('', '>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
+ >>> dt.descr
+ [('name', '>> import numpy as np
+ >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
+ >>> print(dt.fields)
+ {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('flags',
+ """
+ Bit-flags describing how this data type is to be interpreted.
+
+ Bit-masks are in ``numpy._core.multiarray`` as the constants
+ `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,
+ `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation
+ of these flags is in C-API documentation; they are largely useful
+ for user-defined data-types.
+
+ The following example demonstrates that operations on this particular
+ dtype requires Python C-API.
+
+ Examples
+ --------
+
+ >>> import numpy as np
+ >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
+ >>> x.flags
+ 16
+ >>> np._core.multiarray.NEEDS_PYAPI
+ 16
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('hasobject',
+ """
+ Boolean indicating whether this dtype contains any reference-counted
+ objects in any fields or sub-dtypes.
+
+ Recall that what is actually in the ndarray memory representing
+ the Python object is the memory address of that object (a pointer).
+ Special handling may be required, and this attribute is useful for
+ distinguishing data types that may contain arbitrary Python objects
+ and data-types that won't.
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('isbuiltin',
+ """
+ Integer indicating how this dtype relates to the built-in dtypes.
+
+ Read-only.
+
+ = ========================================================================
+ 0 if this is a structured array type, with fields
+ 1 if this is a dtype compiled into numpy (such as ints, floats etc)
+ 2 if the dtype is for a user-defined numpy type
+ A user-defined type uses the numpy C-API machinery to extend
+ numpy to handle a new array type. See
+ :ref:`user.user-defined-data-types` in the NumPy manual.
+ = ========================================================================
+
+ Examples
+ --------
+
+ >>> import numpy as np
+ >>> dt = np.dtype('i2')
+ >>> dt.isbuiltin
+ 1
+ >>> dt = np.dtype('f8')
+ >>> dt.isbuiltin
+ 1
+ >>> dt = np.dtype([('field1', 'f8')])
+ >>> dt.isbuiltin
+ 0
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('isnative',
+ """
+ Boolean indicating whether the byte order of this dtype is native
+ to the platform.
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('isalignedstruct',
+ """
+ Boolean indicating whether the dtype is a struct which maintains
+ field alignment. This flag is sticky, so when combining multiple
+ structs together, it is preserved and produces new dtypes which
+ are also aligned.
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('itemsize',
+ """
+ The element size of this data-type object.
+
+ For 18 of the 21 types this number is fixed by the data-type.
+ For the flexible data-types, this number can be anything.
+
+ Examples
+ --------
+
+ >>> import numpy as np
+ >>> arr = np.array([[1, 2], [3, 4]])
+ >>> arr.dtype
+ dtype('int64')
+ >>> arr.itemsize
+ 8
+
+ >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
+ >>> dt.itemsize
+ 80
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('kind',
+ """
+ A character code (one of 'biufcmMOSUV') identifying the general kind of data.
+
+ = ======================
+ b boolean
+ i signed integer
+ u unsigned integer
+ f floating-point
+ c complex floating-point
+ m timedelta
+ M datetime
+ O object
+ S (byte-)string
+ U Unicode
+ V void
+ = ======================
+
+ Examples
+ --------
+
+ >>> import numpy as np
+ >>> dt = np.dtype('i4')
+ >>> dt.kind
+ 'i'
+ >>> dt = np.dtype('f8')
+ >>> dt.kind
+ 'f'
+ >>> dt = np.dtype([('field1', 'f8')])
+ >>> dt.kind
+ 'V'
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('metadata',
+ """
+ Either ``None`` or a readonly dictionary of metadata (mappingproxy).
+
+ The metadata field can be set using any dictionary at data-type
+ creation. NumPy currently has no uniform approach to propagating
+ metadata; although some array operations preserve it, there is no
+ guarantee that others will.
+
+ .. warning::
+
+ Although used in certain projects, this feature was long undocumented
+ and is not well supported. Some aspects of metadata propagation
+ are expected to change in the future.
+
+ Examples
+ --------
+
+ >>> import numpy as np
+ >>> dt = np.dtype(float, metadata={"key": "value"})
+ >>> dt.metadata["key"]
+ 'value'
+ >>> arr = np.array([1, 2, 3], dtype=dt)
+ >>> arr.dtype.metadata
+ mappingproxy({'key': 'value'})
+
+ Adding arrays with identical datatypes currently preserves the metadata:
+
+ >>> (arr + arr).dtype.metadata
+ mappingproxy({'key': 'value'})
+
+ But if the arrays have different dtype metadata, the metadata may be
+ dropped:
+
+ >>> dt2 = np.dtype(float, metadata={"key2": "value2"})
+ >>> arr2 = np.array([3, 2, 1], dtype=dt2)
+ >>> (arr + arr2).dtype.metadata is None
+ True # The metadata field is cleared so None is returned
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('name',
+ """
+ A bit-width name for this data-type.
+
+ Un-sized flexible data-type objects do not have this attribute.
+
+ Examples
+ --------
+
+ >>> import numpy as np
+ >>> x = np.dtype(float)
+ >>> x.name
+ 'float64'
+ >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
+ >>> x.name
+ 'void640'
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('names',
+ """
+ Ordered list of field names, or ``None`` if there are no fields.
+
+ The names are ordered according to increasing byte offset. This can be
+ used, for example, to walk through all of the named fields in offset order.
+
+ Examples
+ --------
+ >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
+ >>> dt.names
+ ('name', 'grades')
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('num',
+ """
+ A unique number for each of the 21 different built-in types.
+
+ These are roughly ordered from least-to-most precision.
+
+ Examples
+ --------
+
+ >>> import numpy as np
+ >>> dt = np.dtype(str)
+ >>> dt.num
+ 19
+
+ >>> dt = np.dtype(float)
+ >>> dt.num
+ 12
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('shape',
+ """
+ Shape tuple of the sub-array if this data type describes a sub-array,
+ and ``()`` otherwise.
+
+ Examples
+ --------
+
+ >>> import numpy as np
+ >>> dt = np.dtype(('i4', 4))
+ >>> dt.shape
+ (4,)
+
+ >>> dt = np.dtype(('i4', (2, 3)))
+ >>> dt.shape
+ (2, 3)
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('ndim',
+ """
+ Number of dimensions of the sub-array if this data type describes a
+ sub-array, and ``0`` otherwise.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.dtype(float)
+ >>> x.ndim
+ 0
+
+ >>> x = np.dtype((float, 8))
+ >>> x.ndim
+ 1
+
+ >>> x = np.dtype(('i4', (3, 4)))
+ >>> x.ndim
+ 2
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('str',
+ """The array-protocol typestring of this data-type object."""))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('subdtype',
+ """
+ Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
+ None otherwise.
+
+ The *shape* is the fixed shape of the sub-array described by this
+ data type, and *item_dtype* the data type of the array.
+
+ If a field whose dtype object has this attribute is retrieved,
+ then the extra dimensions implied by *shape* are tacked on to
+ the end of the retrieved array.
+
+ See Also
+ --------
+ dtype.base
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = numpy.dtype('8f')
+ >>> x.subdtype
+ (dtype('float32'), (8,))
+
+ >>> x = numpy.dtype('i2')
+ >>> x.subdtype
+ >>>
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('base',
+ """
+ Returns dtype for the base element of the subarrays,
+ regardless of their dimension or shape.
+
+ See Also
+ --------
+ dtype.subdtype
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = numpy.dtype('8f')
+ >>> x.base
+ dtype('float32')
+
+ >>> x = numpy.dtype('i2')
+ >>> x.base
+ dtype('int16')
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('type',
+ """The type object used to instantiate a scalar of this data-type."""))
+
+##############################################################################
+#
+# dtype methods
+#
+##############################################################################
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('newbyteorder',
+ """
+ newbyteorder(new_order='S', /)
+
+ Return a new dtype with a different byte order.
+
+ Changes are also made in all fields and sub-arrays of the data type.
+
+ Parameters
+ ----------
+ new_order : string, optional
+ Byte order to force; a value from the byte order specifications
+ below. The default value ('S') results in swapping the current
+ byte order. `new_order` codes can be any of:
+
+ * 'S' - swap dtype from current to opposite endian
+ * {'<', 'little'} - little endian
+ * {'>', 'big'} - big endian
+ * {'=', 'native'} - native order
+ * {'|', 'I'} - ignore (no change to byte order)
+
+ Returns
+ -------
+ new_dtype : dtype
+ New dtype object with the given change to the byte order.
+
+ Notes
+ -----
+ Changes are also made in all fields and sub-arrays of the data type.
+
+ Examples
+ --------
+ >>> import sys
+ >>> sys_is_le = sys.byteorder == 'little'
+ >>> native_code = '<' if sys_is_le else '>'
+ >>> swapped_code = '>' if sys_is_le else '<'
+ >>> import numpy as np
+ >>> native_dt = np.dtype(native_code+'i2')
+ >>> swapped_dt = np.dtype(swapped_code+'i2')
+ >>> native_dt.newbyteorder('S') == swapped_dt
+ True
+ >>> native_dt.newbyteorder() == swapped_dt
+ True
+ >>> native_dt == swapped_dt.newbyteorder('S')
+ True
+ >>> native_dt == swapped_dt.newbyteorder('=')
+ True
+ >>> native_dt == swapped_dt.newbyteorder('N')
+ True
+ >>> native_dt == native_dt.newbyteorder('|')
+ True
+ >>> np.dtype('>> np.dtype('>> np.dtype('>i2') == native_dt.newbyteorder('>')
+ True
+ >>> np.dtype('>i2') == native_dt.newbyteorder('B')
+ True
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('__class_getitem__',
+ """
+ __class_getitem__(item, /)
+
+ Return a parametrized wrapper around the `~numpy.dtype` type.
+
+ .. versionadded:: 1.22
+
+ Returns
+ -------
+ alias : types.GenericAlias
+ A parametrized `~numpy.dtype` type.
+
+ Examples
+ --------
+ >>> import numpy as np
+
+ >>> np.dtype[np.int64]
+ numpy.dtype[numpy.int64]
+
+ See Also
+ --------
+ :pep:`585` : Type hinting generics in standard collections.
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('__ge__',
+ """
+ __ge__(value, /)
+
+ Return ``self >= value``.
+
+ Equivalent to ``np.can_cast(value, self, casting="safe")``.
+
+ See Also
+ --------
+ can_cast : Returns True if cast between data types can occur according to
+ the casting rule.
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('__le__',
+ """
+ __le__(value, /)
+
+ Return ``self <= value``.
+
+ Equivalent to ``np.can_cast(self, value, casting="safe")``.
+
+ See Also
+ --------
+ can_cast : Returns True if cast between data types can occur according to
+ the casting rule.
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('__gt__',
+ """
+ __ge__(value, /)
+
+ Return ``self > value``.
+
+ Equivalent to
+ ``self != value and np.can_cast(value, self, casting="safe")``.
+
+ See Also
+ --------
+ can_cast : Returns True if cast between data types can occur according to
+ the casting rule.
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('__lt__',
+ """
+ __lt__(value, /)
+
+ Return ``self < value``.
+
+ Equivalent to
+ ``self != value and np.can_cast(self, value, casting="safe")``.
+
+ See Also
+ --------
+ can_cast : Returns True if cast between data types can occur according to
+ the casting rule.
+
+ """))
+
+##############################################################################
+#
+# Datetime-related Methods
+#
+##############################################################################
+
+add_newdoc('numpy._core.multiarray', 'busdaycalendar',
+ """
+ busdaycalendar(weekmask='1111100', holidays=None)
+
+ A business day calendar object that efficiently stores information
+ defining valid days for the busday family of functions.
+
+ The default valid days are Monday through Friday ("business days").
+ A busdaycalendar object can be specified with any set of weekly
+ valid days, plus an optional "holiday" dates that always will be invalid.
+
+ Once a busdaycalendar object is created, the weekmask and holidays
+ cannot be modified.
+
+ Parameters
+ ----------
+ weekmask : str or array_like of bool, optional
+ A seven-element array indicating which of Monday through Sunday are
+ valid days. May be specified as a length-seven list or array, like
+ [1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string
+ like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for
+ weekdays, optionally separated by white space. Valid abbreviations
+ are: Mon Tue Wed Thu Fri Sat Sun
+ holidays : array_like of datetime64[D], optional
+ An array of dates to consider as invalid dates, no matter which
+ weekday they fall upon. Holiday dates may be specified in any
+ order, and NaT (not-a-time) dates are ignored. This list is
+ saved in a normalized form that is suited for fast calculations
+ of valid days.
+
+ Returns
+ -------
+ out : busdaycalendar
+ A business day calendar object containing the specified
+ weekmask and holidays values.
+
+ See Also
+ --------
+ is_busday : Returns a boolean array indicating valid days.
+ busday_offset : Applies an offset counted in valid days.
+ busday_count : Counts how many valid days are in a half-open date range.
+
+ Attributes
+ ----------
+ weekmask : (copy) seven-element array of bool
+ holidays : (copy) sorted array of datetime64[D]
+
+ Notes
+ -----
+ Once a busdaycalendar object is created, you cannot modify the
+ weekmask or holidays. The attributes return copies of internal data.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> # Some important days in July
+ ... bdd = np.busdaycalendar(
+ ... holidays=['2011-07-01', '2011-07-04', '2011-07-17'])
+ >>> # Default is Monday to Friday weekdays
+ ... bdd.weekmask
+ array([ True, True, True, True, True, False, False])
+ >>> # Any holidays already on the weekend are removed
+ ... bdd.holidays
+ array(['2011-07-01', '2011-07-04'], dtype='datetime64[D]')
+ """)
+
+add_newdoc('numpy._core.multiarray', 'busdaycalendar', ('weekmask',
+ """A copy of the seven-element boolean mask indicating valid days."""))
+
+add_newdoc('numpy._core.multiarray', 'busdaycalendar', ('holidays',
+ """A copy of the holiday array indicating additional invalid days."""))
+
+add_newdoc('numpy._core.multiarray', 'normalize_axis_index',
+ """
+ normalize_axis_index(axis, ndim, msg_prefix=None)
+
+ Normalizes an axis index, `axis`, such that is a valid positive index into
+ the shape of array with `ndim` dimensions. Raises an AxisError with an
+ appropriate message if this is not possible.
+
+ Used internally by all axis-checking logic.
+
+ Parameters
+ ----------
+ axis : int
+ The un-normalized index of the axis. Can be negative
+ ndim : int
+ The number of dimensions of the array that `axis` should be normalized
+ against
+ msg_prefix : str
+ A prefix to put before the message, typically the name of the argument
+
+ Returns
+ -------
+ normalized_axis : int
+ The normalized axis index, such that `0 <= normalized_axis < ndim`
+
+ Raises
+ ------
+ AxisError
+ If the axis index is invalid, when `-ndim <= axis < ndim` is false.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from numpy.lib.array_utils import normalize_axis_index
+ >>> normalize_axis_index(0, ndim=3)
+ 0
+ >>> normalize_axis_index(1, ndim=3)
+ 1
+ >>> normalize_axis_index(-1, ndim=3)
+ 2
+
+ >>> normalize_axis_index(3, ndim=3)
+ Traceback (most recent call last):
+ ...
+ numpy.exceptions.AxisError: axis 3 is out of bounds for array ...
+ >>> normalize_axis_index(-4, ndim=3, msg_prefix='axes_arg')
+ Traceback (most recent call last):
+ ...
+ numpy.exceptions.AxisError: axes_arg: axis -4 is out of bounds ...
+ """)
+
+add_newdoc('numpy._core.multiarray', 'datetime_data',
+ """
+ datetime_data(dtype, /)
+
+ Get information about the step size of a date or time type.
+
+ The returned tuple can be passed as the second argument of `numpy.datetime64` and
+ `numpy.timedelta64`.
+
+ Parameters
+ ----------
+ dtype : dtype
+ The dtype object, which must be a `datetime64` or `timedelta64` type.
+
+ Returns
+ -------
+ unit : str
+ The :ref:`datetime unit ` on which this dtype
+ is based.
+ count : int
+ The number of base units in a step.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> dt_25s = np.dtype('timedelta64[25s]')
+ >>> np.datetime_data(dt_25s)
+ ('s', 25)
+ >>> np.array(10, dt_25s).astype('timedelta64[s]')
+ array(250, dtype='timedelta64[s]')
+
+ The result can be used to construct a datetime that uses the same units
+ as a timedelta
+
+ >>> np.datetime64('2010', np.datetime_data(dt_25s))
+ np.datetime64('2010-01-01T00:00:00','25s')
+ """)
+
+
+##############################################################################
+#
+# Documentation for `generic` attributes and methods
+#
+##############################################################################
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ """
+ Base class for numpy scalar types.
+
+ Class from which most (all?) numpy scalar types are derived. For
+ consistency, exposes the same API as `ndarray`, despite many
+ consequent attributes being either "get-only," or completely irrelevant.
+ This is the class from which it is strongly suggested users should derive
+ custom scalar types.
+
+ """)
+
+# Attributes
+
+def refer_to_array_attribute(attr, method=True):
+ docstring = """
+ Scalar {} identical to the corresponding array attribute.
+
+ Please see `ndarray.{}`.
+ """
+
+ return attr, docstring.format("method" if method else "attribute", attr)
+
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('T', method=False))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('base', method=False))
+
+add_newdoc('numpy._core.numerictypes', 'generic', ('data',
+ """Pointer to start of data."""))
+
+add_newdoc('numpy._core.numerictypes', 'generic', ('dtype',
+ """Get array data-descriptor."""))
+
+add_newdoc('numpy._core.numerictypes', 'generic', ('flags',
+ """The integer value of flags."""))
+
+add_newdoc('numpy._core.numerictypes', 'generic', ('flat',
+ """A 1-D view of the scalar."""))
+
+add_newdoc('numpy._core.numerictypes', 'generic', ('imag',
+ """The imaginary part of the scalar."""))
+
+add_newdoc('numpy._core.numerictypes', 'generic', ('itemsize',
+ """The length of one element in bytes."""))
+
+add_newdoc('numpy._core.numerictypes', 'generic', ('ndim',
+ """The number of array dimensions."""))
+
+add_newdoc('numpy._core.numerictypes', 'generic', ('real',
+ """The real part of the scalar."""))
+
+add_newdoc('numpy._core.numerictypes', 'generic', ('shape',
+ """Tuple of array dimensions."""))
+
+add_newdoc('numpy._core.numerictypes', 'generic', ('size',
+ """The number of elements in the gentype."""))
+
+add_newdoc('numpy._core.numerictypes', 'generic', ('strides',
+ """Tuple of bytes steps in each dimension."""))
+
+# Methods
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('all'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('any'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('argmax'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('argmin'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('argsort'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('astype'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('byteswap'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('choose'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('clip'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('compress'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('conjugate'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('copy'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('cumprod'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('cumsum'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('diagonal'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('dump'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('dumps'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('fill'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('flatten'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('getfield'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('item'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('max'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('mean'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('min'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('nonzero'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('prod'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('put'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('ravel'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('repeat'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('reshape'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('resize'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('round'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('searchsorted'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('setfield'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('setflags'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('sort'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('squeeze'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('std'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('sum'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('swapaxes'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('take'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('tofile'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('tolist'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('tostring'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('trace'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('transpose'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('var'))
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ refer_to_array_attribute('view'))
+
+add_newdoc('numpy._core.numerictypes', 'number', ('__class_getitem__',
+ """
+ __class_getitem__(item, /)
+
+ Return a parametrized wrapper around the `~numpy.number` type.
+
+ .. versionadded:: 1.22
+
+ Returns
+ -------
+ alias : types.GenericAlias
+ A parametrized `~numpy.number` type.
+
+ Examples
+ --------
+ >>> from typing import Any
+ >>> import numpy as np
+
+ >>> np.signedinteger[Any]
+ numpy.signedinteger[typing.Any]
+
+ See Also
+ --------
+ :pep:`585` : Type hinting generics in standard collections.
+
+ """))
+
+##############################################################################
+#
+# Documentation for scalar type abstract base classes in type hierarchy
+#
+##############################################################################
+
+
+add_newdoc('numpy._core.numerictypes', 'number',
+ """
+ Abstract base class of all numeric scalar types.
+
+ """)
+
+add_newdoc('numpy._core.numerictypes', 'integer',
+ """
+ Abstract base class of all integer scalar types.
+
+ """)
+
+add_newdoc('numpy._core.numerictypes', 'signedinteger',
+ """
+ Abstract base class of all signed integer scalar types.
+
+ """)
+
+add_newdoc('numpy._core.numerictypes', 'unsignedinteger',
+ """
+ Abstract base class of all unsigned integer scalar types.
+
+ """)
+
+add_newdoc('numpy._core.numerictypes', 'inexact',
+ """
+ Abstract base class of all numeric scalar types with a (potentially)
+ inexact representation of the values in its range, such as
+ floating-point numbers.
+
+ """)
+
+add_newdoc('numpy._core.numerictypes', 'floating',
+ """
+ Abstract base class of all floating-point scalar types.
+
+ """)
+
+add_newdoc('numpy._core.numerictypes', 'complexfloating',
+ """
+ Abstract base class of all complex number scalar types that are made up of
+ floating-point numbers.
+
+ """)
+
+add_newdoc('numpy._core.numerictypes', 'flexible',
+ """
+ Abstract base class of all scalar types without predefined length.
+ The actual size of these types depends on the specific `numpy.dtype`
+ instantiation.
+
+ """)
+
+add_newdoc('numpy._core.numerictypes', 'character',
+ """
+ Abstract base class of all character string scalar types.
+
+ """)
+
+add_newdoc('numpy._core.multiarray', 'StringDType',
+ """
+ StringDType(*, na_object=np._NoValue, coerce=True)
+
+ Create a StringDType instance.
+
+ StringDType can be used to store UTF-8 encoded variable-width strings in
+ a NumPy array.
+
+ Parameters
+ ----------
+ na_object : object, optional
+ Object used to represent missing data. If unset, the array will not
+ use a missing data sentinel.
+ coerce : bool, optional
+ Whether or not items in an array-like passed to an array creation
+ function that are neither a str or str subtype should be coerced to
+ str. Defaults to True. If set to False, creating a StringDType
+ array from an array-like containing entries that are not already
+ strings will raise an error.
+
+ Examples
+ --------
+
+ >>> import numpy as np
+
+ >>> from numpy.dtypes import StringDType
+ >>> np.array(["hello", "world"], dtype=StringDType())
+ array(["hello", "world"], dtype=StringDType())
+
+ >>> arr = np.array(["hello", None, "world"],
+ ... dtype=StringDType(na_object=None))
+ >>> arr
+ array(["hello", None, "world"], dtype=StringDType(na_object=None))
+ >>> arr[1] is None
+ True
+
+ >>> arr = np.array(["hello", np.nan, "world"],
+ ... dtype=StringDType(na_object=np.nan))
+ >>> np.isnan(arr)
+ array([False, True, False])
+
+ >>> np.array([1.2, object(), "hello world"],
+ ... dtype=StringDType(coerce=True))
+ ValueError: StringDType only allows string data when string coercion
+ is disabled.
+
+ >>> np.array(["hello", "world"], dtype=StringDType(coerce=True))
+ array(["hello", "world"], dtype=StringDType(coerce=True))
+ """)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_add_newdocs.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_add_newdocs.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..b23c3b1adedd9b9b9f24930ac4940501a4a3dc91
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_add_newdocs.pyi
@@ -0,0 +1,3 @@
+from .overrides import get_array_function_like_doc as get_array_function_like_doc
+
+def refer_to_array_attribute(attr: str, method: bool = True) -> tuple[str, str]: ...
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_add_newdocs_scalars.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_add_newdocs_scalars.py
new file mode 100644
index 0000000000000000000000000000000000000000..52035e9fb4ae6e0819b69eea516e5b8b14293b17
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_add_newdocs_scalars.py
@@ -0,0 +1,389 @@
+"""
+This file is separate from ``_add_newdocs.py`` so that it can be mocked out by
+our sphinx ``conf.py`` during doc builds, where we want to avoid showing
+platform-dependent information.
+"""
+import sys
+import os
+from numpy._core import dtype
+from numpy._core import numerictypes as _numerictypes
+from numpy._core.function_base import add_newdoc
+
+##############################################################################
+#
+# Documentation for concrete scalar classes
+#
+##############################################################################
+
+def numeric_type_aliases(aliases):
+ def type_aliases_gen():
+ for alias, doc in aliases:
+ try:
+ alias_type = getattr(_numerictypes, alias)
+ except AttributeError:
+ # The set of aliases that actually exist varies between platforms
+ pass
+ else:
+ yield (alias_type, alias, doc)
+ return list(type_aliases_gen())
+
+
+possible_aliases = numeric_type_aliases([
+ ('int8', '8-bit signed integer (``-128`` to ``127``)'),
+ ('int16', '16-bit signed integer (``-32_768`` to ``32_767``)'),
+ ('int32', '32-bit signed integer (``-2_147_483_648`` to ``2_147_483_647``)'),
+ ('int64', '64-bit signed integer (``-9_223_372_036_854_775_808`` to ``9_223_372_036_854_775_807``)'),
+ ('intp', 'Signed integer large enough to fit pointer, compatible with C ``intptr_t``'),
+ ('uint8', '8-bit unsigned integer (``0`` to ``255``)'),
+ ('uint16', '16-bit unsigned integer (``0`` to ``65_535``)'),
+ ('uint32', '32-bit unsigned integer (``0`` to ``4_294_967_295``)'),
+ ('uint64', '64-bit unsigned integer (``0`` to ``18_446_744_073_709_551_615``)'),
+ ('uintp', 'Unsigned integer large enough to fit pointer, compatible with C ``uintptr_t``'),
+ ('float16', '16-bit-precision floating-point number type: sign bit, 5 bits exponent, 10 bits mantissa'),
+ ('float32', '32-bit-precision floating-point number type: sign bit, 8 bits exponent, 23 bits mantissa'),
+ ('float64', '64-bit precision floating-point number type: sign bit, 11 bits exponent, 52 bits mantissa'),
+ ('float96', '96-bit extended-precision floating-point number type'),
+ ('float128', '128-bit extended-precision floating-point number type'),
+ ('complex64', 'Complex number type composed of 2 32-bit-precision floating-point numbers'),
+ ('complex128', 'Complex number type composed of 2 64-bit-precision floating-point numbers'),
+ ('complex192', 'Complex number type composed of 2 96-bit extended-precision floating-point numbers'),
+ ('complex256', 'Complex number type composed of 2 128-bit extended-precision floating-point numbers'),
+ ])
+
+
+def _get_platform_and_machine():
+ try:
+ system, _, _, _, machine = os.uname()
+ except AttributeError:
+ system = sys.platform
+ if system == 'win32':
+ machine = os.environ.get('PROCESSOR_ARCHITEW6432', '') \
+ or os.environ.get('PROCESSOR_ARCHITECTURE', '')
+ else:
+ machine = 'unknown'
+ return system, machine
+
+
+_system, _machine = _get_platform_and_machine()
+_doc_alias_string = f":Alias on this platform ({_system} {_machine}):"
+
+
+def add_newdoc_for_scalar_type(obj, fixed_aliases, doc):
+ # note: `:field: value` is rST syntax which renders as field lists.
+ o = getattr(_numerictypes, obj)
+
+ character_code = dtype(o).char
+ canonical_name_doc = "" if obj == o.__name__ else \
+ f":Canonical name: `numpy.{obj}`\n "
+ if fixed_aliases:
+ alias_doc = ''.join(f":Alias: `numpy.{alias}`\n "
+ for alias in fixed_aliases)
+ else:
+ alias_doc = ''
+ alias_doc += ''.join(f"{_doc_alias_string} `numpy.{alias}`: {doc}.\n "
+ for (alias_type, alias, doc) in possible_aliases if alias_type is o)
+
+ docstring = f"""
+ {doc.strip()}
+
+ :Character code: ``'{character_code}'``
+ {canonical_name_doc}{alias_doc}
+ """
+
+ add_newdoc('numpy._core.numerictypes', obj, docstring)
+
+
+_bool_docstring = (
+ """
+ Boolean type (True or False), stored as a byte.
+
+ .. warning::
+
+ The :class:`bool` type is not a subclass of the :class:`int_` type
+ (the :class:`bool` is not even a number type). This is different
+ than Python's default implementation of :class:`bool` as a
+ sub-class of :class:`int`.
+ """
+)
+
+add_newdoc_for_scalar_type('bool', [], _bool_docstring)
+
+add_newdoc_for_scalar_type('bool_', [], _bool_docstring)
+
+add_newdoc_for_scalar_type('byte', [],
+ """
+ Signed integer type, compatible with C ``char``.
+ """)
+
+add_newdoc_for_scalar_type('short', [],
+ """
+ Signed integer type, compatible with C ``short``.
+ """)
+
+add_newdoc_for_scalar_type('intc', [],
+ """
+ Signed integer type, compatible with C ``int``.
+ """)
+
+# TODO: These docs probably need an if to highlight the default rather than
+# the C-types (and be correct).
+add_newdoc_for_scalar_type('int_', [],
+ """
+ Default signed integer type, 64bit on 64bit systems and 32bit on 32bit
+ systems.
+ """)
+
+add_newdoc_for_scalar_type('longlong', [],
+ """
+ Signed integer type, compatible with C ``long long``.
+ """)
+
+add_newdoc_for_scalar_type('ubyte', [],
+ """
+ Unsigned integer type, compatible with C ``unsigned char``.
+ """)
+
+add_newdoc_for_scalar_type('ushort', [],
+ """
+ Unsigned integer type, compatible with C ``unsigned short``.
+ """)
+
+add_newdoc_for_scalar_type('uintc', [],
+ """
+ Unsigned integer type, compatible with C ``unsigned int``.
+ """)
+
+add_newdoc_for_scalar_type('uint', [],
+ """
+ Unsigned signed integer type, 64bit on 64bit systems and 32bit on 32bit
+ systems.
+ """)
+
+add_newdoc_for_scalar_type('ulonglong', [],
+ """
+ Signed integer type, compatible with C ``unsigned long long``.
+ """)
+
+add_newdoc_for_scalar_type('half', [],
+ """
+ Half-precision floating-point number type.
+ """)
+
+add_newdoc_for_scalar_type('single', [],
+ """
+ Single-precision floating-point number type, compatible with C ``float``.
+ """)
+
+add_newdoc_for_scalar_type('double', [],
+ """
+ Double-precision floating-point number type, compatible with Python
+ :class:`float` and C ``double``.
+ """)
+
+add_newdoc_for_scalar_type('longdouble', [],
+ """
+ Extended-precision floating-point number type, compatible with C
+ ``long double`` but not necessarily with IEEE 754 quadruple-precision.
+ """)
+
+add_newdoc_for_scalar_type('csingle', [],
+ """
+ Complex number type composed of two single-precision floating-point
+ numbers.
+ """)
+
+add_newdoc_for_scalar_type('cdouble', [],
+ """
+ Complex number type composed of two double-precision floating-point
+ numbers, compatible with Python :class:`complex`.
+ """)
+
+add_newdoc_for_scalar_type('clongdouble', [],
+ """
+ Complex number type composed of two extended-precision floating-point
+ numbers.
+ """)
+
+add_newdoc_for_scalar_type('object_', [],
+ """
+ Any Python object.
+ """)
+
+add_newdoc_for_scalar_type('str_', [],
+ r"""
+ A unicode string.
+
+ This type strips trailing null codepoints.
+
+ >>> s = np.str_("abc\x00")
+ >>> s
+ 'abc'
+
+ Unlike the builtin :class:`str`, this supports the
+ :ref:`python:bufferobjects`, exposing its contents as UCS4:
+
+ >>> m = memoryview(np.str_("abc"))
+ >>> m.format
+ '3w'
+ >>> m.tobytes()
+ b'a\x00\x00\x00b\x00\x00\x00c\x00\x00\x00'
+ """)
+
+add_newdoc_for_scalar_type('bytes_', [],
+ r"""
+ A byte string.
+
+ When used in arrays, this type strips trailing null bytes.
+ """)
+
+add_newdoc_for_scalar_type('void', [],
+ r"""
+ np.void(length_or_data, /, dtype=None)
+
+ Create a new structured or unstructured void scalar.
+
+ Parameters
+ ----------
+ length_or_data : int, array-like, bytes-like, object
+ One of multiple meanings (see notes). The length or
+ bytes data of an unstructured void. Or alternatively,
+ the data to be stored in the new scalar when `dtype`
+ is provided.
+ This can be an array-like, in which case an array may
+ be returned.
+ dtype : dtype, optional
+ If provided the dtype of the new scalar. This dtype must
+ be "void" dtype (i.e. a structured or unstructured void,
+ see also :ref:`defining-structured-types`).
+
+ .. versionadded:: 1.24
+
+ Notes
+ -----
+ For historical reasons and because void scalars can represent both
+ arbitrary byte data and structured dtypes, the void constructor
+ has three calling conventions:
+
+ 1. ``np.void(5)`` creates a ``dtype="V5"`` scalar filled with five
+ ``\0`` bytes. The 5 can be a Python or NumPy integer.
+ 2. ``np.void(b"bytes-like")`` creates a void scalar from the byte string.
+ The dtype itemsize will match the byte string length, here ``"V10"``.
+ 3. When a ``dtype=`` is passed the call is roughly the same as an
+ array creation. However, a void scalar rather than array is returned.
+
+ Please see the examples which show all three different conventions.
+
+ Examples
+ --------
+ >>> np.void(5)
+ np.void(b'\x00\x00\x00\x00\x00')
+ >>> np.void(b'abcd')
+ np.void(b'\x61\x62\x63\x64')
+ >>> np.void((3.2, b'eggs'), dtype="d,S5")
+ np.void((3.2, b'eggs'), dtype=[('f0', '>> np.void(3, dtype=[('x', np.int8), ('y', np.int8)])
+ np.void((3, 3), dtype=[('x', 'i1'), ('y', 'i1')])
+
+ """)
+
+add_newdoc_for_scalar_type('datetime64', [],
+ """
+ If created from a 64-bit integer, it represents an offset from
+ ``1970-01-01T00:00:00``.
+ If created from string, the string can be in ISO 8601 date
+ or datetime format.
+
+ When parsing a string to create a datetime object, if the string contains
+ a trailing timezone (A 'Z' or a timezone offset), the timezone will be
+ dropped and a User Warning is given.
+
+ Datetime64 objects should be considered to be UTC and therefore have an
+ offset of +0000.
+
+ >>> np.datetime64(10, 'Y')
+ np.datetime64('1980')
+ >>> np.datetime64('1980', 'Y')
+ np.datetime64('1980')
+ >>> np.datetime64(10, 'D')
+ np.datetime64('1970-01-11')
+
+ See :ref:`arrays.datetime` for more information.
+ """)
+
+add_newdoc_for_scalar_type('timedelta64', [],
+ """
+ A timedelta stored as a 64-bit integer.
+
+ See :ref:`arrays.datetime` for more information.
+ """)
+
+add_newdoc('numpy._core.numerictypes', "integer", ('is_integer',
+ """
+ integer.is_integer() -> bool
+
+ Return ``True`` if the number is finite with integral value.
+
+ .. versionadded:: 1.22
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.int64(-2).is_integer()
+ True
+ >>> np.uint32(5).is_integer()
+ True
+ """))
+
+# TODO: work out how to put this on the base class, np.floating
+for float_name in ('half', 'single', 'double', 'longdouble'):
+ add_newdoc('numpy._core.numerictypes', float_name, ('as_integer_ratio',
+ """
+ {ftype}.as_integer_ratio() -> (int, int)
+
+ Return a pair of integers, whose ratio is exactly equal to the original
+ floating point number, and with a positive denominator.
+ Raise `OverflowError` on infinities and a `ValueError` on NaNs.
+
+ >>> np.{ftype}(10.0).as_integer_ratio()
+ (10, 1)
+ >>> np.{ftype}(0.0).as_integer_ratio()
+ (0, 1)
+ >>> np.{ftype}(-.25).as_integer_ratio()
+ (-1, 4)
+ """.format(ftype=float_name)))
+
+ add_newdoc('numpy._core.numerictypes', float_name, ('is_integer',
+ f"""
+ {float_name}.is_integer() -> bool
+
+ Return ``True`` if the floating point number is finite with integral
+ value, and ``False`` otherwise.
+
+ .. versionadded:: 1.22
+
+ Examples
+ --------
+ >>> np.{float_name}(-2.0).is_integer()
+ True
+ >>> np.{float_name}(3.2).is_integer()
+ False
+ """))
+
+for int_name in ('int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32',
+ 'int64', 'uint64', 'int64', 'uint64', 'int64', 'uint64'):
+ # Add negative examples for signed cases by checking typecode
+ add_newdoc('numpy._core.numerictypes', int_name, ('bit_count',
+ f"""
+ {int_name}.bit_count() -> int
+
+ Computes the number of 1-bits in the absolute value of the input.
+ Analogous to the builtin `int.bit_count` or ``popcount`` in C++.
+
+ Examples
+ --------
+ >>> np.{int_name}(127).bit_count()
+ 7""" +
+ (f"""
+ >>> np.{int_name}(-127).bit_count()
+ 7
+ """ if dtype(int_name).char.islower() else "")))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_add_newdocs_scalars.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_add_newdocs_scalars.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..4a06c9b07d748d0f6d064ff9e0fdf7839118e143
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_add_newdocs_scalars.pyi
@@ -0,0 +1,16 @@
+from collections.abc import Iterable
+from typing import Final
+
+import numpy as np
+
+possible_aliases: Final[list[tuple[type[np.number], str, str]]] = ...
+_system: Final[str] = ...
+_machine: Final[str] = ...
+_doc_alias_string: Final[str] = ...
+_bool_docstring: Final[str] = ...
+int_name: str = ...
+float_name: str = ...
+
+def numeric_type_aliases(aliases: list[tuple[str, str]]) -> list[tuple[type[np.number], str, str]]: ...
+def add_newdoc_for_scalar_type(obj: str, fixed_aliases: Iterable[str], doc: str) -> None: ...
+def _get_platform_and_machine() -> tuple[str, str]: ...
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_asarray.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_asarray.py
new file mode 100644
index 0000000000000000000000000000000000000000..28ee8eaa8c5805bab297d24dfb4e9a1c8d4d8917
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_asarray.py
@@ -0,0 +1,135 @@
+"""
+Functions in the ``as*array`` family that promote array-likes into arrays.
+
+`require` fits this category despite its name not matching this pattern.
+"""
+from .overrides import (
+ array_function_dispatch,
+ finalize_array_function_like,
+ set_module,
+)
+from .multiarray import array, asanyarray
+
+
+__all__ = ["require"]
+
+
+POSSIBLE_FLAGS = {
+ 'C': 'C', 'C_CONTIGUOUS': 'C', 'CONTIGUOUS': 'C',
+ 'F': 'F', 'F_CONTIGUOUS': 'F', 'FORTRAN': 'F',
+ 'A': 'A', 'ALIGNED': 'A',
+ 'W': 'W', 'WRITEABLE': 'W',
+ 'O': 'O', 'OWNDATA': 'O',
+ 'E': 'E', 'ENSUREARRAY': 'E'
+}
+
+
+@finalize_array_function_like
+@set_module('numpy')
+def require(a, dtype=None, requirements=None, *, like=None):
+ """
+ Return an ndarray of the provided type that satisfies requirements.
+
+ This function is useful to be sure that an array with the correct flags
+ is returned for passing to compiled code (perhaps through ctypes).
+
+ Parameters
+ ----------
+ a : array_like
+ The object to be converted to a type-and-requirement-satisfying array.
+ dtype : data-type
+ The required data-type. If None preserve the current dtype. If your
+ application requires the data to be in native byteorder, include
+ a byteorder specification as a part of the dtype specification.
+ requirements : str or sequence of str
+ The requirements list can be any of the following
+
+ * 'F_CONTIGUOUS' ('F') - ensure a Fortran-contiguous array
+ * 'C_CONTIGUOUS' ('C') - ensure a C-contiguous array
+ * 'ALIGNED' ('A') - ensure a data-type aligned array
+ * 'WRITEABLE' ('W') - ensure a writable array
+ * 'OWNDATA' ('O') - ensure an array that owns its own data
+ * 'ENSUREARRAY', ('E') - ensure a base array, instead of a subclass
+ ${ARRAY_FUNCTION_LIKE}
+
+ .. versionadded:: 1.20.0
+
+ Returns
+ -------
+ out : ndarray
+ Array with specified requirements and type if given.
+
+ See Also
+ --------
+ asarray : Convert input to an ndarray.
+ asanyarray : Convert to an ndarray, but pass through ndarray subclasses.
+ ascontiguousarray : Convert input to a contiguous array.
+ asfortranarray : Convert input to an ndarray with column-major
+ memory order.
+ ndarray.flags : Information about the memory layout of the array.
+
+ Notes
+ -----
+ The returned array will be guaranteed to have the listed requirements
+ by making a copy if needed.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.arange(6).reshape(2,3)
+ >>> x.flags
+ C_CONTIGUOUS : True
+ F_CONTIGUOUS : False
+ OWNDATA : False
+ WRITEABLE : True
+ ALIGNED : True
+ WRITEBACKIFCOPY : False
+
+ >>> y = np.require(x, dtype=np.float32, requirements=['A', 'O', 'W', 'F'])
+ >>> y.flags
+ C_CONTIGUOUS : False
+ F_CONTIGUOUS : True
+ OWNDATA : True
+ WRITEABLE : True
+ ALIGNED : True
+ WRITEBACKIFCOPY : False
+
+ """
+ if like is not None:
+ return _require_with_like(
+ like,
+ a,
+ dtype=dtype,
+ requirements=requirements,
+ )
+
+ if not requirements:
+ return asanyarray(a, dtype=dtype)
+
+ requirements = {POSSIBLE_FLAGS[x.upper()] for x in requirements}
+
+ if 'E' in requirements:
+ requirements.remove('E')
+ subok = False
+ else:
+ subok = True
+
+ order = 'A'
+ if requirements >= {'C', 'F'}:
+ raise ValueError('Cannot specify both "C" and "F" order')
+ elif 'F' in requirements:
+ order = 'F'
+ requirements.remove('F')
+ elif 'C' in requirements:
+ order = 'C'
+ requirements.remove('C')
+
+ arr = array(a, dtype=dtype, order=order, copy=None, subok=subok)
+
+ for prop in requirements:
+ if not arr.flags[prop]:
+ return arr.copy(order)
+ return arr
+
+
+_require_with_like = array_function_dispatch()(require)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_asarray.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_asarray.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..356d31b009e837817b7027357783d0207e29bc0e
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_asarray.pyi
@@ -0,0 +1,41 @@
+from collections.abc import Iterable
+from typing import Any, TypeAlias, TypeVar, overload, Literal
+
+from numpy._typing import NDArray, DTypeLike, _SupportsArrayFunc
+
+_ArrayType = TypeVar("_ArrayType", bound=NDArray[Any])
+
+_Requirements: TypeAlias = Literal[
+ "C", "C_CONTIGUOUS", "CONTIGUOUS",
+ "F", "F_CONTIGUOUS", "FORTRAN",
+ "A", "ALIGNED",
+ "W", "WRITEABLE",
+ "O", "OWNDATA"
+]
+_E: TypeAlias = Literal["E", "ENSUREARRAY"]
+_RequirementsWithE: TypeAlias = _Requirements | _E
+
+@overload
+def require(
+ a: _ArrayType,
+ dtype: None = ...,
+ requirements: None | _Requirements | Iterable[_Requirements] = ...,
+ *,
+ like: _SupportsArrayFunc = ...
+) -> _ArrayType: ...
+@overload
+def require(
+ a: object,
+ dtype: DTypeLike = ...,
+ requirements: _E | Iterable[_RequirementsWithE] = ...,
+ *,
+ like: _SupportsArrayFunc = ...
+) -> NDArray[Any]: ...
+@overload
+def require(
+ a: object,
+ dtype: DTypeLike = ...,
+ requirements: None | _Requirements | Iterable[_Requirements] = ...,
+ *,
+ like: _SupportsArrayFunc = ...
+) -> NDArray[Any]: ...
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_dtype.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_dtype.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee9b965902633c3834de86d7e6ec4747cda1183f
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_dtype.py
@@ -0,0 +1,374 @@
+"""
+A place for code to be called from the implementation of np.dtype
+
+String handling is much easier to do correctly in python.
+"""
+import numpy as np
+
+
+_kind_to_stem = {
+ 'u': 'uint',
+ 'i': 'int',
+ 'c': 'complex',
+ 'f': 'float',
+ 'b': 'bool',
+ 'V': 'void',
+ 'O': 'object',
+ 'M': 'datetime',
+ 'm': 'timedelta',
+ 'S': 'bytes',
+ 'U': 'str',
+}
+
+
+def _kind_name(dtype):
+ try:
+ return _kind_to_stem[dtype.kind]
+ except KeyError as e:
+ raise RuntimeError(
+ "internal dtype error, unknown kind {!r}"
+ .format(dtype.kind)
+ ) from None
+
+
+def __str__(dtype):
+ if dtype.fields is not None:
+ return _struct_str(dtype, include_align=True)
+ elif dtype.subdtype:
+ return _subarray_str(dtype)
+ elif issubclass(dtype.type, np.flexible) or not dtype.isnative:
+ return dtype.str
+ else:
+ return dtype.name
+
+
+def __repr__(dtype):
+ arg_str = _construction_repr(dtype, include_align=False)
+ if dtype.isalignedstruct:
+ arg_str = arg_str + ", align=True"
+ return "dtype({})".format(arg_str)
+
+
+def _unpack_field(dtype, offset, title=None):
+ """
+ Helper function to normalize the items in dtype.fields.
+
+ Call as:
+
+ dtype, offset, title = _unpack_field(*dtype.fields[name])
+ """
+ return dtype, offset, title
+
+
+def _isunsized(dtype):
+ # PyDataType_ISUNSIZED
+ return dtype.itemsize == 0
+
+
+def _construction_repr(dtype, include_align=False, short=False):
+ """
+ Creates a string repr of the dtype, excluding the 'dtype()' part
+ surrounding the object. This object may be a string, a list, or
+ a dict depending on the nature of the dtype. This
+ is the object passed as the first parameter to the dtype
+ constructor, and if no additional constructor parameters are
+ given, will reproduce the exact memory layout.
+
+ Parameters
+ ----------
+ short : bool
+ If true, this creates a shorter repr using 'kind' and 'itemsize',
+ instead of the longer type name.
+
+ include_align : bool
+ If true, this includes the 'align=True' parameter
+ inside the struct dtype construction dict when needed. Use this flag
+ if you want a proper repr string without the 'dtype()' part around it.
+
+ If false, this does not preserve the
+ 'align=True' parameter or sticky NPY_ALIGNED_STRUCT flag for
+ struct arrays like the regular repr does, because the 'align'
+ flag is not part of first dtype constructor parameter. This
+ mode is intended for a full 'repr', where the 'align=True' is
+ provided as the second parameter.
+ """
+ if dtype.fields is not None:
+ return _struct_str(dtype, include_align=include_align)
+ elif dtype.subdtype:
+ return _subarray_str(dtype)
+ else:
+ return _scalar_str(dtype, short=short)
+
+
+def _scalar_str(dtype, short):
+ byteorder = _byte_order_str(dtype)
+
+ if dtype.type == np.bool:
+ if short:
+ return "'?'"
+ else:
+ return "'bool'"
+
+ elif dtype.type == np.object_:
+ # The object reference may be different sizes on different
+ # platforms, so it should never include the itemsize here.
+ return "'O'"
+
+ elif dtype.type == np.bytes_:
+ if _isunsized(dtype):
+ return "'S'"
+ else:
+ return "'S%d'" % dtype.itemsize
+
+ elif dtype.type == np.str_:
+ if _isunsized(dtype):
+ return "'%sU'" % byteorder
+ else:
+ return "'%sU%d'" % (byteorder, dtype.itemsize / 4)
+
+ elif dtype.type == str:
+ return "'T'"
+
+ elif not type(dtype)._legacy:
+ return f"'{byteorder}{type(dtype).__name__}{dtype.itemsize * 8}'"
+
+ # unlike the other types, subclasses of void are preserved - but
+ # historically the repr does not actually reveal the subclass
+ elif issubclass(dtype.type, np.void):
+ if _isunsized(dtype):
+ return "'V'"
+ else:
+ return "'V%d'" % dtype.itemsize
+
+ elif dtype.type == np.datetime64:
+ return "'%sM8%s'" % (byteorder, _datetime_metadata_str(dtype))
+
+ elif dtype.type == np.timedelta64:
+ return "'%sm8%s'" % (byteorder, _datetime_metadata_str(dtype))
+
+ elif np.issubdtype(dtype, np.number):
+ # Short repr with endianness, like '' """
+ # hack to obtain the native and swapped byte order characters
+ swapped = np.dtype(int).newbyteorder('S')
+ native = swapped.newbyteorder('S')
+
+ byteorder = dtype.byteorder
+ if byteorder == '=':
+ return native.byteorder
+ if byteorder == 'S':
+ # TODO: this path can never be reached
+ return swapped.byteorder
+ elif byteorder == '|':
+ return ''
+ else:
+ return byteorder
+
+
+def _datetime_metadata_str(dtype):
+ # TODO: this duplicates the C metastr_to_unicode functionality
+ unit, count = np.datetime_data(dtype)
+ if unit == 'generic':
+ return ''
+ elif count == 1:
+ return '[{}]'.format(unit)
+ else:
+ return '[{}{}]'.format(count, unit)
+
+
+def _struct_dict_str(dtype, includealignedflag):
+ # unpack the fields dictionary into ls
+ names = dtype.names
+ fld_dtypes = []
+ offsets = []
+ titles = []
+ for name in names:
+ fld_dtype, offset, title = _unpack_field(*dtype.fields[name])
+ fld_dtypes.append(fld_dtype)
+ offsets.append(offset)
+ titles.append(title)
+
+ # Build up a string to make the dictionary
+
+ if np._core.arrayprint._get_legacy_print_mode() <= 121:
+ colon = ":"
+ fieldsep = ","
+ else:
+ colon = ": "
+ fieldsep = ", "
+
+ # First, the names
+ ret = "{'names'%s[" % colon
+ ret += fieldsep.join(repr(name) for name in names)
+
+ # Second, the formats
+ ret += "], 'formats'%s[" % colon
+ ret += fieldsep.join(
+ _construction_repr(fld_dtype, short=True) for fld_dtype in fld_dtypes)
+
+ # Third, the offsets
+ ret += "], 'offsets'%s[" % colon
+ ret += fieldsep.join("%d" % offset for offset in offsets)
+
+ # Fourth, the titles
+ if any(title is not None for title in titles):
+ ret += "], 'titles'%s[" % colon
+ ret += fieldsep.join(repr(title) for title in titles)
+
+ # Fifth, the itemsize
+ ret += "], 'itemsize'%s%d" % (colon, dtype.itemsize)
+
+ if (includealignedflag and dtype.isalignedstruct):
+ # Finally, the aligned flag
+ ret += ", 'aligned'%sTrue}" % colon
+ else:
+ ret += "}"
+
+ return ret
+
+
+def _aligned_offset(offset, alignment):
+ # round up offset:
+ return - (-offset // alignment) * alignment
+
+
+def _is_packed(dtype):
+ """
+ Checks whether the structured data type in 'dtype'
+ has a simple layout, where all the fields are in order,
+ and follow each other with no alignment padding.
+
+ When this returns true, the dtype can be reconstructed
+ from a list of the field names and dtypes with no additional
+ dtype parameters.
+
+ Duplicates the C `is_dtype_struct_simple_unaligned_layout` function.
+ """
+ align = dtype.isalignedstruct
+ max_alignment = 1
+ total_offset = 0
+ for name in dtype.names:
+ fld_dtype, fld_offset, title = _unpack_field(*dtype.fields[name])
+
+ if align:
+ total_offset = _aligned_offset(total_offset, fld_dtype.alignment)
+ max_alignment = max(max_alignment, fld_dtype.alignment)
+
+ if fld_offset != total_offset:
+ return False
+ total_offset += fld_dtype.itemsize
+
+ if align:
+ total_offset = _aligned_offset(total_offset, max_alignment)
+
+ return total_offset == dtype.itemsize
+
+
+def _struct_list_str(dtype):
+ items = []
+ for name in dtype.names:
+ fld_dtype, fld_offset, title = _unpack_field(*dtype.fields[name])
+
+ item = "("
+ if title is not None:
+ item += "({!r}, {!r}), ".format(title, name)
+ else:
+ item += "{!r}, ".format(name)
+ # Special case subarray handling here
+ if fld_dtype.subdtype is not None:
+ base, shape = fld_dtype.subdtype
+ item += "{}, {}".format(
+ _construction_repr(base, short=True),
+ shape
+ )
+ else:
+ item += _construction_repr(fld_dtype, short=True)
+
+ item += ")"
+ items.append(item)
+
+ return "[" + ", ".join(items) + "]"
+
+
+def _struct_str(dtype, include_align):
+ # The list str representation can't include the 'align=' flag,
+ # so if it is requested and the struct has the aligned flag set,
+ # we must use the dict str instead.
+ if not (include_align and dtype.isalignedstruct) and _is_packed(dtype):
+ sub = _struct_list_str(dtype)
+
+ else:
+ sub = _struct_dict_str(dtype, include_align)
+
+ # If the data type isn't the default, void, show it
+ if dtype.type != np.void:
+ return "({t.__module__}.{t.__name__}, {f})".format(t=dtype.type, f=sub)
+ else:
+ return sub
+
+
+def _subarray_str(dtype):
+ base, shape = dtype.subdtype
+ return "({}, {})".format(
+ _construction_repr(base, short=True),
+ shape
+ )
+
+
+def _name_includes_bit_suffix(dtype):
+ if dtype.type == np.object_:
+ # pointer size varies by system, best to omit it
+ return False
+ elif dtype.type == np.bool:
+ # implied
+ return False
+ elif dtype.type is None:
+ return True
+ elif np.issubdtype(dtype, np.flexible) and _isunsized(dtype):
+ # unspecified
+ return False
+ else:
+ return True
+
+
+def _name_get(dtype):
+ # provides dtype.name.__get__, documented as returning a "bit name"
+
+ if dtype.isbuiltin == 2:
+ # user dtypes don't promise to do anything special
+ return dtype.type.__name__
+
+ if not type(dtype)._legacy:
+ name = type(dtype).__name__
+
+ elif issubclass(dtype.type, np.void):
+ # historically, void subclasses preserve their name, eg `record64`
+ name = dtype.type.__name__
+ else:
+ name = _kind_name(dtype)
+
+ # append bit counts
+ if _name_includes_bit_suffix(dtype):
+ name += "{}".format(dtype.itemsize * 8)
+
+ # append metadata to datetimes
+ if dtype.type in (np.datetime64, np.timedelta64):
+ name += _datetime_metadata_str(dtype)
+
+ return name
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_dtype.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_dtype.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..c3e966e3f51729aca69365ce3520ab23e3c1a7ea
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_dtype.pyi
@@ -0,0 +1,58 @@
+from typing import Any, Final, TypeAlias, TypedDict, overload, type_check_only
+from typing import Literal as L
+
+from typing_extensions import ReadOnly, TypeVar
+
+import numpy as np
+
+###
+
+_T = TypeVar("_T")
+
+_Name: TypeAlias = L["uint", "int", "complex", "float", "bool", "void", "object", "datetime", "timedelta", "bytes", "str"]
+
+@type_check_only
+class _KindToStemType(TypedDict):
+ u: ReadOnly[L["uint"]]
+ i: ReadOnly[L["int"]]
+ c: ReadOnly[L["complex"]]
+ f: ReadOnly[L["float"]]
+ b: ReadOnly[L["bool"]]
+ V: ReadOnly[L["void"]]
+ O: ReadOnly[L["object"]]
+ M: ReadOnly[L["datetime"]]
+ m: ReadOnly[L["timedelta"]]
+ S: ReadOnly[L["bytes"]]
+ U: ReadOnly[L["str"]]
+
+###
+
+_kind_to_stem: Final[_KindToStemType] = ...
+
+#
+def _kind_name(dtype: np.dtype[Any]) -> _Name: ...
+def __str__(dtype: np.dtype[Any]) -> str: ...
+def __repr__(dtype: np.dtype[Any]) -> str: ...
+
+#
+def _isunsized(dtype: np.dtype[Any]) -> bool: ...
+def _is_packed(dtype: np.dtype[Any]) -> bool: ...
+def _name_includes_bit_suffix(dtype: np.dtype[Any]) -> bool: ...
+
+#
+def _construction_repr(dtype: np.dtype[Any], include_align: bool = False, short: bool = False) -> str: ...
+def _scalar_str(dtype: np.dtype[Any], short: bool) -> str: ...
+def _byte_order_str(dtype: np.dtype[Any]) -> str: ...
+def _datetime_metadata_str(dtype: np.dtype[Any]) -> str: ...
+def _struct_dict_str(dtype: np.dtype[Any], includealignedflag: bool) -> str: ...
+def _struct_list_str(dtype: np.dtype[Any]) -> str: ...
+def _struct_str(dtype: np.dtype[Any], include_align: bool) -> str: ...
+def _subarray_str(dtype: np.dtype[Any]) -> str: ...
+def _name_get(dtype: np.dtype[Any]) -> str: ...
+
+#
+@overload
+def _unpack_field(dtype: np.dtype[Any], offset: int, title: _T) -> tuple[np.dtype[Any], int, _T]: ...
+@overload
+def _unpack_field(dtype: np.dtype[Any], offset: int, title: None = None) -> tuple[np.dtype[Any], int, None]: ...
+def _aligned_offset(offset: int, alignment: int) -> int: ...
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_dtype_ctypes.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_dtype_ctypes.py
new file mode 100644
index 0000000000000000000000000000000000000000..fef1e0db35f2fcd97269e25ca442b881a8a1a757
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_dtype_ctypes.py
@@ -0,0 +1,120 @@
+"""
+Conversion from ctypes to dtype.
+
+In an ideal world, we could achieve this through the PEP3118 buffer protocol,
+something like::
+
+ def dtype_from_ctypes_type(t):
+ # needed to ensure that the shape of `t` is within memoryview.format
+ class DummyStruct(ctypes.Structure):
+ _fields_ = [('a', t)]
+
+ # empty to avoid memory allocation
+ ctype_0 = (DummyStruct * 0)()
+ mv = memoryview(ctype_0)
+
+ # convert the struct, and slice back out the field
+ return _dtype_from_pep3118(mv.format)['a']
+
+Unfortunately, this fails because:
+
+* ctypes cannot handle length-0 arrays with PEP3118 (bpo-32782)
+* PEP3118 cannot represent unions, but both numpy and ctypes can
+* ctypes cannot handle big-endian structs with PEP3118 (bpo-32780)
+"""
+
+# We delay-import ctypes for distributions that do not include it.
+# While this module is not used unless the user passes in ctypes
+# members, it is eagerly imported from numpy/_core/__init__.py.
+import numpy as np
+
+
+def _from_ctypes_array(t):
+ return np.dtype((dtype_from_ctypes_type(t._type_), (t._length_,)))
+
+
+def _from_ctypes_structure(t):
+ for item in t._fields_:
+ if len(item) > 2:
+ raise TypeError(
+ "ctypes bitfields have no dtype equivalent")
+
+ if hasattr(t, "_pack_"):
+ import ctypes
+ formats = []
+ offsets = []
+ names = []
+ current_offset = 0
+ for fname, ftyp in t._fields_:
+ names.append(fname)
+ formats.append(dtype_from_ctypes_type(ftyp))
+ # Each type has a default offset, this is platform dependent
+ # for some types.
+ effective_pack = min(t._pack_, ctypes.alignment(ftyp))
+ current_offset = (
+ (current_offset + effective_pack - 1) // effective_pack
+ ) * effective_pack
+ offsets.append(current_offset)
+ current_offset += ctypes.sizeof(ftyp)
+
+ return np.dtype(dict(
+ formats=formats,
+ offsets=offsets,
+ names=names,
+ itemsize=ctypes.sizeof(t)))
+ else:
+ fields = []
+ for fname, ftyp in t._fields_:
+ fields.append((fname, dtype_from_ctypes_type(ftyp)))
+
+ # by default, ctypes structs are aligned
+ return np.dtype(fields, align=True)
+
+
+def _from_ctypes_scalar(t):
+ """
+ Return the dtype type with endianness included if it's the case
+ """
+ if getattr(t, '__ctype_be__', None) is t:
+ return np.dtype('>' + t._type_)
+ elif getattr(t, '__ctype_le__', None) is t:
+ return np.dtype('<' + t._type_)
+ else:
+ return np.dtype(t._type_)
+
+
+def _from_ctypes_union(t):
+ import ctypes
+ formats = []
+ offsets = []
+ names = []
+ for fname, ftyp in t._fields_:
+ names.append(fname)
+ formats.append(dtype_from_ctypes_type(ftyp))
+ offsets.append(0) # Union fields are offset to 0
+
+ return np.dtype(dict(
+ formats=formats,
+ offsets=offsets,
+ names=names,
+ itemsize=ctypes.sizeof(t)))
+
+
+def dtype_from_ctypes_type(t):
+ """
+ Construct a dtype object from a ctypes type
+ """
+ import _ctypes
+ if issubclass(t, _ctypes.Array):
+ return _from_ctypes_array(t)
+ elif issubclass(t, _ctypes._Pointer):
+ raise TypeError("ctypes pointers have no dtype equivalent")
+ elif issubclass(t, _ctypes.Structure):
+ return _from_ctypes_structure(t)
+ elif issubclass(t, _ctypes.Union):
+ return _from_ctypes_union(t)
+ elif isinstance(getattr(t, '_type_', None), str):
+ return _from_ctypes_scalar(t)
+ else:
+ raise NotImplementedError(
+ "Unknown ctypes type {}".format(t.__name__))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_dtype_ctypes.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_dtype_ctypes.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..69438a2c1b4c98cda8b36d45440fd459f118ebb9
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_dtype_ctypes.pyi
@@ -0,0 +1,83 @@
+import _ctypes
+import ctypes as ct
+from typing import Any, overload
+
+import numpy as np
+
+#
+@overload
+def dtype_from_ctypes_type(t: type[_ctypes.Array[Any] | _ctypes.Structure]) -> np.dtype[np.void]: ...
+@overload
+def dtype_from_ctypes_type(t: type[ct.c_bool]) -> np.dtype[np.bool]: ...
+@overload
+def dtype_from_ctypes_type(t: type[ct.c_int8 | ct.c_byte]) -> np.dtype[np.int8]: ...
+@overload
+def dtype_from_ctypes_type(t: type[ct.c_uint8 | ct.c_ubyte]) -> np.dtype[np.uint8]: ...
+@overload
+def dtype_from_ctypes_type(t: type[ct.c_int16 | ct.c_short]) -> np.dtype[np.int16]: ...
+@overload
+def dtype_from_ctypes_type(t: type[ct.c_uint16 | ct.c_ushort]) -> np.dtype[np.uint16]: ...
+@overload
+def dtype_from_ctypes_type(t: type[ct.c_int32 | ct.c_int]) -> np.dtype[np.int32]: ...
+@overload
+def dtype_from_ctypes_type(t: type[ct.c_uint32 | ct.c_uint]) -> np.dtype[np.uint32]: ...
+@overload
+def dtype_from_ctypes_type(t: type[ct.c_ssize_t | ct.c_long]) -> np.dtype[np.int32 | np.int64]: ...
+@overload
+def dtype_from_ctypes_type(t: type[ct.c_size_t | ct.c_ulong]) -> np.dtype[np.uint32 | np.uint64]: ...
+@overload
+def dtype_from_ctypes_type(t: type[ct.c_int64 | ct.c_longlong]) -> np.dtype[np.int64]: ...
+@overload
+def dtype_from_ctypes_type(t: type[ct.c_uint64 | ct.c_ulonglong]) -> np.dtype[np.uint64]: ...
+@overload
+def dtype_from_ctypes_type(t: type[ct.c_float]) -> np.dtype[np.float32]: ...
+@overload
+def dtype_from_ctypes_type(t: type[ct.c_double]) -> np.dtype[np.float64]: ...
+@overload
+def dtype_from_ctypes_type(t: type[ct.c_longdouble]) -> np.dtype[np.longdouble]: ...
+@overload
+def dtype_from_ctypes_type(t: type[ct.c_char]) -> np.dtype[np.bytes_]: ...
+@overload
+def dtype_from_ctypes_type(t: type[ct.py_object[Any]]) -> np.dtype[np.object_]: ...
+
+# NOTE: the complex ctypes on python>=3.14 are not yet supported at runtim, see
+# https://github.com/numpy/numpy/issues/28360
+
+#
+def _from_ctypes_array(t: type[_ctypes.Array[Any]]) -> np.dtype[np.void]: ...
+def _from_ctypes_structure(t: type[_ctypes.Structure]) -> np.dtype[np.void]: ...
+def _from_ctypes_union(t: type[_ctypes.Union]) -> np.dtype[np.void]: ...
+
+# keep in sync with `dtype_from_ctypes_type` (minus the first overload)
+@overload
+def _from_ctypes_scalar(t: type[ct.c_bool]) -> np.dtype[np.bool]: ...
+@overload
+def _from_ctypes_scalar(t: type[ct.c_int8 | ct.c_byte]) -> np.dtype[np.int8]: ...
+@overload
+def _from_ctypes_scalar(t: type[ct.c_uint8 | ct.c_ubyte]) -> np.dtype[np.uint8]: ...
+@overload
+def _from_ctypes_scalar(t: type[ct.c_int16 | ct.c_short]) -> np.dtype[np.int16]: ...
+@overload
+def _from_ctypes_scalar(t: type[ct.c_uint16 | ct.c_ushort]) -> np.dtype[np.uint16]: ...
+@overload
+def _from_ctypes_scalar(t: type[ct.c_int32 | ct.c_int]) -> np.dtype[np.int32]: ...
+@overload
+def _from_ctypes_scalar(t: type[ct.c_uint32 | ct.c_uint]) -> np.dtype[np.uint32]: ...
+@overload
+def _from_ctypes_scalar(t: type[ct.c_ssize_t | ct.c_long]) -> np.dtype[np.int32 | np.int64]: ...
+@overload
+def _from_ctypes_scalar(t: type[ct.c_size_t | ct.c_ulong]) -> np.dtype[np.uint32 | np.uint64]: ...
+@overload
+def _from_ctypes_scalar(t: type[ct.c_int64 | ct.c_longlong]) -> np.dtype[np.int64]: ...
+@overload
+def _from_ctypes_scalar(t: type[ct.c_uint64 | ct.c_ulonglong]) -> np.dtype[np.uint64]: ...
+@overload
+def _from_ctypes_scalar(t: type[ct.c_float]) -> np.dtype[np.float32]: ...
+@overload
+def _from_ctypes_scalar(t: type[ct.c_double]) -> np.dtype[np.float64]: ...
+@overload
+def _from_ctypes_scalar(t: type[ct.c_longdouble]) -> np.dtype[np.longdouble]: ...
+@overload
+def _from_ctypes_scalar(t: type[ct.c_char]) -> np.dtype[np.bytes_]: ...
+@overload
+def _from_ctypes_scalar(t: type[ct.py_object[Any]]) -> np.dtype[np.object_]: ...
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_exceptions.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..87d4213a6d42cf090f8db75571244840dd68cd5a
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_exceptions.py
@@ -0,0 +1,172 @@
+"""
+Various richly-typed exceptions, that also help us deal with string formatting
+in python where it's easier.
+
+By putting the formatting in `__str__`, we also avoid paying the cost for
+users who silence the exceptions.
+"""
+from .._utils import set_module
+
+def _unpack_tuple(tup):
+ if len(tup) == 1:
+ return tup[0]
+ else:
+ return tup
+
+
+def _display_as_base(cls):
+ """
+ A decorator that makes an exception class look like its base.
+
+ We use this to hide subclasses that are implementation details - the user
+ should catch the base type, which is what the traceback will show them.
+
+ Classes decorated with this decorator are subject to removal without a
+ deprecation warning.
+ """
+ assert issubclass(cls, Exception)
+ cls.__name__ = cls.__base__.__name__
+ return cls
+
+
+class UFuncTypeError(TypeError):
+ """ Base class for all ufunc exceptions """
+ def __init__(self, ufunc):
+ self.ufunc = ufunc
+
+
+@_display_as_base
+class _UFuncNoLoopError(UFuncTypeError):
+ """ Thrown when a ufunc loop cannot be found """
+ def __init__(self, ufunc, dtypes):
+ super().__init__(ufunc)
+ self.dtypes = tuple(dtypes)
+
+ def __str__(self):
+ return (
+ "ufunc {!r} did not contain a loop with signature matching types "
+ "{!r} -> {!r}"
+ ).format(
+ self.ufunc.__name__,
+ _unpack_tuple(self.dtypes[:self.ufunc.nin]),
+ _unpack_tuple(self.dtypes[self.ufunc.nin:])
+ )
+
+
+@_display_as_base
+class _UFuncBinaryResolutionError(_UFuncNoLoopError):
+ """ Thrown when a binary resolution fails """
+ def __init__(self, ufunc, dtypes):
+ super().__init__(ufunc, dtypes)
+ assert len(self.dtypes) == 2
+
+ def __str__(self):
+ return (
+ "ufunc {!r} cannot use operands with types {!r} and {!r}"
+ ).format(
+ self.ufunc.__name__, *self.dtypes
+ )
+
+
+@_display_as_base
+class _UFuncCastingError(UFuncTypeError):
+ def __init__(self, ufunc, casting, from_, to):
+ super().__init__(ufunc)
+ self.casting = casting
+ self.from_ = from_
+ self.to = to
+
+
+@_display_as_base
+class _UFuncInputCastingError(_UFuncCastingError):
+ """ Thrown when a ufunc input cannot be casted """
+ def __init__(self, ufunc, casting, from_, to, i):
+ super().__init__(ufunc, casting, from_, to)
+ self.in_i = i
+
+ def __str__(self):
+ # only show the number if more than one input exists
+ i_str = "{} ".format(self.in_i) if self.ufunc.nin != 1 else ""
+ return (
+ "Cannot cast ufunc {!r} input {}from {!r} to {!r} with casting "
+ "rule {!r}"
+ ).format(
+ self.ufunc.__name__, i_str, self.from_, self.to, self.casting
+ )
+
+
+@_display_as_base
+class _UFuncOutputCastingError(_UFuncCastingError):
+ """ Thrown when a ufunc output cannot be casted """
+ def __init__(self, ufunc, casting, from_, to, i):
+ super().__init__(ufunc, casting, from_, to)
+ self.out_i = i
+
+ def __str__(self):
+ # only show the number if more than one output exists
+ i_str = "{} ".format(self.out_i) if self.ufunc.nout != 1 else ""
+ return (
+ "Cannot cast ufunc {!r} output {}from {!r} to {!r} with casting "
+ "rule {!r}"
+ ).format(
+ self.ufunc.__name__, i_str, self.from_, self.to, self.casting
+ )
+
+
+@_display_as_base
+class _ArrayMemoryError(MemoryError):
+ """ Thrown when an array cannot be allocated"""
+ def __init__(self, shape, dtype):
+ self.shape = shape
+ self.dtype = dtype
+
+ @property
+ def _total_size(self):
+ num_bytes = self.dtype.itemsize
+ for dim in self.shape:
+ num_bytes *= dim
+ return num_bytes
+
+ @staticmethod
+ def _size_to_string(num_bytes):
+ """ Convert a number of bytes into a binary size string """
+
+ # https://en.wikipedia.org/wiki/Binary_prefix
+ LOG2_STEP = 10
+ STEP = 1024
+ units = ['bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB']
+
+ unit_i = max(num_bytes.bit_length() - 1, 1) // LOG2_STEP
+ unit_val = 1 << (unit_i * LOG2_STEP)
+ n_units = num_bytes / unit_val
+ del unit_val
+
+ # ensure we pick a unit that is correct after rounding
+ if round(n_units) == STEP:
+ unit_i += 1
+ n_units /= STEP
+
+ # deal with sizes so large that we don't have units for them
+ if unit_i >= len(units):
+ new_unit_i = len(units) - 1
+ n_units *= 1 << ((unit_i - new_unit_i) * LOG2_STEP)
+ unit_i = new_unit_i
+
+ unit_name = units[unit_i]
+ # format with a sensible number of digits
+ if unit_i == 0:
+ # no decimal point on bytes
+ return '{:.0f} {}'.format(n_units, unit_name)
+ elif round(n_units) < 1000:
+ # 3 significant figures, if none are dropped to the left of the .
+ return '{:#.3g} {}'.format(n_units, unit_name)
+ else:
+ # just give all the digits otherwise
+ return '{:#.0f} {}'.format(n_units, unit_name)
+
+ def __str__(self):
+ size_str = self._size_to_string(self._total_size)
+ return (
+ "Unable to allocate {} for an array with shape {} and data type {}"
+ .format(size_str, self.shape, self.dtype)
+ )
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_exceptions.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_exceptions.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..5abfc779c2120734c29d017844dd6ecc2b171bdb
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_exceptions.pyi
@@ -0,0 +1,73 @@
+from collections.abc import Iterable
+from typing import Any, Final, overload
+
+from typing_extensions import TypeVar, Unpack
+
+import numpy as np
+from numpy import _CastingKind
+from numpy._utils import set_module as set_module
+
+###
+
+_T = TypeVar("_T")
+_TupleT = TypeVar("_TupleT", bound=tuple[()] | tuple[Any, Any, Unpack[tuple[Any, ...]]])
+_ExceptionT = TypeVar("_ExceptionT", bound=Exception)
+
+###
+
+class UFuncTypeError(TypeError):
+ ufunc: Final[np.ufunc]
+ def __init__(self, /, ufunc: np.ufunc) -> None: ...
+
+class _UFuncNoLoopError(UFuncTypeError):
+ dtypes: tuple[np.dtype[Any], ...]
+ def __init__(self, /, ufunc: np.ufunc, dtypes: Iterable[np.dtype[Any]]) -> None: ...
+
+class _UFuncBinaryResolutionError(_UFuncNoLoopError):
+ dtypes: tuple[np.dtype[Any], np.dtype[Any]]
+ def __init__(self, /, ufunc: np.ufunc, dtypes: Iterable[np.dtype[Any]]) -> None: ...
+
+class _UFuncCastingError(UFuncTypeError):
+ casting: Final[_CastingKind]
+ from_: Final[np.dtype[Any]]
+ to: Final[np.dtype[Any]]
+ def __init__(self, /, ufunc: np.ufunc, casting: _CastingKind, from_: np.dtype[Any], to: np.dtype[Any]) -> None: ...
+
+class _UFuncInputCastingError(_UFuncCastingError):
+ in_i: Final[int]
+ def __init__(
+ self,
+ /,
+ ufunc: np.ufunc,
+ casting: _CastingKind,
+ from_: np.dtype[Any],
+ to: np.dtype[Any],
+ i: int,
+ ) -> None: ...
+
+class _UFuncOutputCastingError(_UFuncCastingError):
+ out_i: Final[int]
+ def __init__(
+ self,
+ /,
+ ufunc: np.ufunc,
+ casting: _CastingKind,
+ from_: np.dtype[Any],
+ to: np.dtype[Any],
+ i: int,
+ ) -> None: ...
+
+class _ArrayMemoryError(MemoryError):
+ shape: tuple[int, ...]
+ dtype: np.dtype[Any]
+ def __init__(self, /, shape: tuple[int, ...], dtype: np.dtype[Any]) -> None: ...
+ @property
+ def _total_size(self) -> int: ...
+ @staticmethod
+ def _size_to_string(num_bytes: int) -> str: ...
+
+@overload
+def _unpack_tuple(tup: tuple[_T]) -> _T: ...
+@overload
+def _unpack_tuple(tup: _TupleT) -> _TupleT: ...
+def _display_as_base(cls: type[_ExceptionT]) -> type[_ExceptionT]: ...
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_internal.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_internal.py
new file mode 100644
index 0000000000000000000000000000000000000000..c0142bf44f034f7f635e07841e00f451c3907dfd
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_internal.py
@@ -0,0 +1,963 @@
+"""
+A place for internal code
+
+Some things are more easily handled Python.
+
+"""
+import ast
+import math
+import re
+import sys
+import warnings
+
+from ..exceptions import DTypePromotionError
+from .multiarray import dtype, array, ndarray, promote_types, StringDType
+from numpy import _NoValue
+try:
+ import ctypes
+except ImportError:
+ ctypes = None
+
+IS_PYPY = sys.implementation.name == 'pypy'
+
+if sys.byteorder == 'little':
+ _nbo = '<'
+else:
+ _nbo = '>'
+
+def _makenames_list(adict, align):
+ allfields = []
+
+ for fname, obj in adict.items():
+ n = len(obj)
+ if not isinstance(obj, tuple) or n not in (2, 3):
+ raise ValueError("entry not a 2- or 3- tuple")
+ if n > 2 and obj[2] == fname:
+ continue
+ num = int(obj[1])
+ if num < 0:
+ raise ValueError("invalid offset.")
+ format = dtype(obj[0], align=align)
+ if n > 2:
+ title = obj[2]
+ else:
+ title = None
+ allfields.append((fname, format, num, title))
+ # sort by offsets
+ allfields.sort(key=lambda x: x[2])
+ names = [x[0] for x in allfields]
+ formats = [x[1] for x in allfields]
+ offsets = [x[2] for x in allfields]
+ titles = [x[3] for x in allfields]
+
+ return names, formats, offsets, titles
+
+# Called in PyArray_DescrConverter function when
+# a dictionary without "names" and "formats"
+# fields is used as a data-type descriptor.
+def _usefields(adict, align):
+ try:
+ names = adict[-1]
+ except KeyError:
+ names = None
+ if names is None:
+ names, formats, offsets, titles = _makenames_list(adict, align)
+ else:
+ formats = []
+ offsets = []
+ titles = []
+ for name in names:
+ res = adict[name]
+ formats.append(res[0])
+ offsets.append(res[1])
+ if len(res) > 2:
+ titles.append(res[2])
+ else:
+ titles.append(None)
+
+ return dtype({"names": names,
+ "formats": formats,
+ "offsets": offsets,
+ "titles": titles}, align)
+
+
+# construct an array_protocol descriptor list
+# from the fields attribute of a descriptor
+# This calls itself recursively but should eventually hit
+# a descriptor that has no fields and then return
+# a simple typestring
+
+def _array_descr(descriptor):
+ fields = descriptor.fields
+ if fields is None:
+ subdtype = descriptor.subdtype
+ if subdtype is None:
+ if descriptor.metadata is None:
+ return descriptor.str
+ else:
+ new = descriptor.metadata.copy()
+ if new:
+ return (descriptor.str, new)
+ else:
+ return descriptor.str
+ else:
+ return (_array_descr(subdtype[0]), subdtype[1])
+
+ names = descriptor.names
+ ordered_fields = [fields[x] + (x,) for x in names]
+ result = []
+ offset = 0
+ for field in ordered_fields:
+ if field[1] > offset:
+ num = field[1] - offset
+ result.append(('', f'|V{num}'))
+ offset += num
+ elif field[1] < offset:
+ raise ValueError(
+ "dtype.descr is not defined for types with overlapping or "
+ "out-of-order fields")
+ if len(field) > 3:
+ name = (field[2], field[3])
+ else:
+ name = field[2]
+ if field[0].subdtype:
+ tup = (name, _array_descr(field[0].subdtype[0]),
+ field[0].subdtype[1])
+ else:
+ tup = (name, _array_descr(field[0]))
+ offset += field[0].itemsize
+ result.append(tup)
+
+ if descriptor.itemsize > offset:
+ num = descriptor.itemsize - offset
+ result.append(('', f'|V{num}'))
+
+ return result
+
+
+# format_re was originally from numarray by J. Todd Miller
+
+format_re = re.compile(r'(?P[<>|=]?)'
+ r'(?P *[(]?[ ,0-9]*[)]? *)'
+ r'(?P[<>|=]?)'
+ r'(?P[A-Za-z0-9.?]*(?:\[[a-zA-Z0-9,.]+\])?)')
+sep_re = re.compile(r'\s*,\s*')
+space_re = re.compile(r'\s+$')
+
+# astr is a string (perhaps comma separated)
+
+_convorder = {'=': _nbo}
+
+def _commastring(astr):
+ startindex = 0
+ result = []
+ islist = False
+ while startindex < len(astr):
+ mo = format_re.match(astr, pos=startindex)
+ try:
+ (order1, repeats, order2, dtype) = mo.groups()
+ except (TypeError, AttributeError):
+ raise ValueError(
+ f'format number {len(result)+1} of "{astr}" is not recognized'
+ ) from None
+ startindex = mo.end()
+ # Separator or ending padding
+ if startindex < len(astr):
+ if space_re.match(astr, pos=startindex):
+ startindex = len(astr)
+ else:
+ mo = sep_re.match(astr, pos=startindex)
+ if not mo:
+ raise ValueError(
+ 'format number %d of "%s" is not recognized' %
+ (len(result)+1, astr))
+ startindex = mo.end()
+ islist = True
+
+ if order2 == '':
+ order = order1
+ elif order1 == '':
+ order = order2
+ else:
+ order1 = _convorder.get(order1, order1)
+ order2 = _convorder.get(order2, order2)
+ if (order1 != order2):
+ raise ValueError(
+ 'inconsistent byte-order specification %s and %s' %
+ (order1, order2))
+ order = order1
+
+ if order in ('|', '=', _nbo):
+ order = ''
+ dtype = order + dtype
+ if repeats == '':
+ newitem = dtype
+ else:
+ if (repeats[0] == "(" and repeats[-1] == ")"
+ and repeats[1:-1].strip() != ""
+ and "," not in repeats):
+ warnings.warn(
+ 'Passing in a parenthesized single number for repeats '
+ 'is deprecated; pass either a single number or indicate '
+ 'a tuple with a comma, like "(2,)".', DeprecationWarning,
+ stacklevel=2)
+ newitem = (dtype, ast.literal_eval(repeats))
+
+ result.append(newitem)
+
+ return result if islist else result[0]
+
+class dummy_ctype:
+
+ def __init__(self, cls):
+ self._cls = cls
+
+ def __mul__(self, other):
+ return self
+
+ def __call__(self, *other):
+ return self._cls(other)
+
+ def __eq__(self, other):
+ return self._cls == other._cls
+
+ def __ne__(self, other):
+ return self._cls != other._cls
+
+def _getintp_ctype():
+ val = _getintp_ctype.cache
+ if val is not None:
+ return val
+ if ctypes is None:
+ import numpy as np
+ val = dummy_ctype(np.intp)
+ else:
+ char = dtype('n').char
+ if char == 'i':
+ val = ctypes.c_int
+ elif char == 'l':
+ val = ctypes.c_long
+ elif char == 'q':
+ val = ctypes.c_longlong
+ else:
+ val = ctypes.c_long
+ _getintp_ctype.cache = val
+ return val
+
+
+_getintp_ctype.cache = None
+
+# Used for .ctypes attribute of ndarray
+
+class _missing_ctypes:
+ def cast(self, num, obj):
+ return num.value
+
+ class c_void_p:
+ def __init__(self, ptr):
+ self.value = ptr
+
+
+class _ctypes:
+ def __init__(self, array, ptr=None):
+ self._arr = array
+
+ if ctypes:
+ self._ctypes = ctypes
+ self._data = self._ctypes.c_void_p(ptr)
+ else:
+ # fake a pointer-like object that holds onto the reference
+ self._ctypes = _missing_ctypes()
+ self._data = self._ctypes.c_void_p(ptr)
+ self._data._objects = array
+
+ if self._arr.ndim == 0:
+ self._zerod = True
+ else:
+ self._zerod = False
+
+ def data_as(self, obj):
+ """
+ Return the data pointer cast to a particular c-types object.
+ For example, calling ``self._as_parameter_`` is equivalent to
+ ``self.data_as(ctypes.c_void_p)``. Perhaps you want to use
+ the data as a pointer to a ctypes array of floating-point data:
+ ``self.data_as(ctypes.POINTER(ctypes.c_double))``.
+
+ The returned pointer will keep a reference to the array.
+ """
+ # _ctypes.cast function causes a circular reference of self._data in
+ # self._data._objects. Attributes of self._data cannot be released
+ # until gc.collect is called. Make a copy of the pointer first then
+ # let it hold the array reference. This is a workaround to circumvent
+ # the CPython bug https://bugs.python.org/issue12836.
+ ptr = self._ctypes.cast(self._data, obj)
+ ptr._arr = self._arr
+ return ptr
+
+ def shape_as(self, obj):
+ """
+ Return the shape tuple as an array of some other c-types
+ type. For example: ``self.shape_as(ctypes.c_short)``.
+ """
+ if self._zerod:
+ return None
+ return (obj*self._arr.ndim)(*self._arr.shape)
+
+ def strides_as(self, obj):
+ """
+ Return the strides tuple as an array of some other
+ c-types type. For example: ``self.strides_as(ctypes.c_longlong)``.
+ """
+ if self._zerod:
+ return None
+ return (obj*self._arr.ndim)(*self._arr.strides)
+
+ @property
+ def data(self):
+ """
+ A pointer to the memory area of the array as a Python integer.
+ This memory area may contain data that is not aligned, or not in
+ correct byte-order. The memory area may not even be writeable.
+ The array flags and data-type of this array should be respected
+ when passing this attribute to arbitrary C-code to avoid trouble
+ that can include Python crashing. User Beware! The value of this
+ attribute is exactly the same as:
+ ``self._array_interface_['data'][0]``.
+
+ Note that unlike ``data_as``, a reference won't be kept to the array:
+ code like ``ctypes.c_void_p((a + b).ctypes.data)`` will result in a
+ pointer to a deallocated array, and should be spelt
+ ``(a + b).ctypes.data_as(ctypes.c_void_p)``
+ """
+ return self._data.value
+
+ @property
+ def shape(self):
+ """
+ (c_intp*self.ndim): A ctypes array of length self.ndim where
+ the basetype is the C-integer corresponding to ``dtype('p')`` on this
+ platform (see `~numpy.ctypeslib.c_intp`). This base-type could be
+ `ctypes.c_int`, `ctypes.c_long`, or `ctypes.c_longlong` depending on
+ the platform. The ctypes array contains the shape of
+ the underlying array.
+ """
+ return self.shape_as(_getintp_ctype())
+
+ @property
+ def strides(self):
+ """
+ (c_intp*self.ndim): A ctypes array of length self.ndim where
+ the basetype is the same as for the shape attribute. This ctypes
+ array contains the strides information from the underlying array.
+ This strides information is important for showing how many bytes
+ must be jumped to get to the next element in the array.
+ """
+ return self.strides_as(_getintp_ctype())
+
+ @property
+ def _as_parameter_(self):
+ """
+ Overrides the ctypes semi-magic method
+
+ Enables `c_func(some_array.ctypes)`
+ """
+ return self.data_as(ctypes.c_void_p)
+
+ # Numpy 1.21.0, 2021-05-18
+
+ def get_data(self):
+ """Deprecated getter for the `_ctypes.data` property.
+
+ .. deprecated:: 1.21
+ """
+ warnings.warn('"get_data" is deprecated. Use "data" instead',
+ DeprecationWarning, stacklevel=2)
+ return self.data
+
+ def get_shape(self):
+ """Deprecated getter for the `_ctypes.shape` property.
+
+ .. deprecated:: 1.21
+ """
+ warnings.warn('"get_shape" is deprecated. Use "shape" instead',
+ DeprecationWarning, stacklevel=2)
+ return self.shape
+
+ def get_strides(self):
+ """Deprecated getter for the `_ctypes.strides` property.
+
+ .. deprecated:: 1.21
+ """
+ warnings.warn('"get_strides" is deprecated. Use "strides" instead',
+ DeprecationWarning, stacklevel=2)
+ return self.strides
+
+ def get_as_parameter(self):
+ """Deprecated getter for the `_ctypes._as_parameter_` property.
+
+ .. deprecated:: 1.21
+ """
+ warnings.warn(
+ '"get_as_parameter" is deprecated. Use "_as_parameter_" instead',
+ DeprecationWarning, stacklevel=2,
+ )
+ return self._as_parameter_
+
+
+def _newnames(datatype, order):
+ """
+ Given a datatype and an order object, return a new names tuple, with the
+ order indicated
+ """
+ oldnames = datatype.names
+ nameslist = list(oldnames)
+ if isinstance(order, str):
+ order = [order]
+ seen = set()
+ if isinstance(order, (list, tuple)):
+ for name in order:
+ try:
+ nameslist.remove(name)
+ except ValueError:
+ if name in seen:
+ raise ValueError(f"duplicate field name: {name}") from None
+ else:
+ raise ValueError(f"unknown field name: {name}") from None
+ seen.add(name)
+ return tuple(list(order) + nameslist)
+ raise ValueError(f"unsupported order value: {order}")
+
+def _copy_fields(ary):
+ """Return copy of structured array with padding between fields removed.
+
+ Parameters
+ ----------
+ ary : ndarray
+ Structured array from which to remove padding bytes
+
+ Returns
+ -------
+ ary_copy : ndarray
+ Copy of ary with padding bytes removed
+ """
+ dt = ary.dtype
+ copy_dtype = {'names': dt.names,
+ 'formats': [dt.fields[name][0] for name in dt.names]}
+ return array(ary, dtype=copy_dtype, copy=True)
+
+def _promote_fields(dt1, dt2):
+ """ Perform type promotion for two structured dtypes.
+
+ Parameters
+ ----------
+ dt1 : structured dtype
+ First dtype.
+ dt2 : structured dtype
+ Second dtype.
+
+ Returns
+ -------
+ out : dtype
+ The promoted dtype
+
+ Notes
+ -----
+ If one of the inputs is aligned, the result will be. The titles of
+ both descriptors must match (point to the same field).
+ """
+ # Both must be structured and have the same names in the same order
+ if (dt1.names is None or dt2.names is None) or dt1.names != dt2.names:
+ raise DTypePromotionError(
+ f"field names `{dt1.names}` and `{dt2.names}` mismatch.")
+
+ # if both are identical, we can (maybe!) just return the same dtype.
+ identical = dt1 is dt2
+ new_fields = []
+ for name in dt1.names:
+ field1 = dt1.fields[name]
+ field2 = dt2.fields[name]
+ new_descr = promote_types(field1[0], field2[0])
+ identical = identical and new_descr is field1[0]
+
+ # Check that the titles match (if given):
+ if field1[2:] != field2[2:]:
+ raise DTypePromotionError(
+ f"field titles of field '{name}' mismatch")
+ if len(field1) == 2:
+ new_fields.append((name, new_descr))
+ else:
+ new_fields.append(((field1[2], name), new_descr))
+
+ res = dtype(new_fields, align=dt1.isalignedstruct or dt2.isalignedstruct)
+
+ # Might as well preserve identity (and metadata) if the dtype is identical
+ # and the itemsize, offsets are also unmodified. This could probably be
+ # sped up, but also probably just be removed entirely.
+ if identical and res.itemsize == dt1.itemsize:
+ for name in dt1.names:
+ if dt1.fields[name][1] != res.fields[name][1]:
+ return res # the dtype changed.
+ return dt1
+
+ return res
+
+
+def _getfield_is_safe(oldtype, newtype, offset):
+ """ Checks safety of getfield for object arrays.
+
+ As in _view_is_safe, we need to check that memory containing objects is not
+ reinterpreted as a non-object datatype and vice versa.
+
+ Parameters
+ ----------
+ oldtype : data-type
+ Data type of the original ndarray.
+ newtype : data-type
+ Data type of the field being accessed by ndarray.getfield
+ offset : int
+ Offset of the field being accessed by ndarray.getfield
+
+ Raises
+ ------
+ TypeError
+ If the field access is invalid
+
+ """
+ if newtype.hasobject or oldtype.hasobject:
+ if offset == 0 and newtype == oldtype:
+ return
+ if oldtype.names is not None:
+ for name in oldtype.names:
+ if (oldtype.fields[name][1] == offset and
+ oldtype.fields[name][0] == newtype):
+ return
+ raise TypeError("Cannot get/set field of an object array")
+ return
+
+def _view_is_safe(oldtype, newtype):
+ """ Checks safety of a view involving object arrays, for example when
+ doing::
+
+ np.zeros(10, dtype=oldtype).view(newtype)
+
+ Parameters
+ ----------
+ oldtype : data-type
+ Data type of original ndarray
+ newtype : data-type
+ Data type of the view
+
+ Raises
+ ------
+ TypeError
+ If the new type is incompatible with the old type.
+
+ """
+
+ # if the types are equivalent, there is no problem.
+ # for example: dtype((np.record, 'i4,i4')) == dtype((np.void, 'i4,i4'))
+ if oldtype == newtype:
+ return
+
+ if newtype.hasobject or oldtype.hasobject:
+ raise TypeError("Cannot change data-type for array of references.")
+ return
+
+
+# Given a string containing a PEP 3118 format specifier,
+# construct a NumPy dtype
+
+_pep3118_native_map = {
+ '?': '?',
+ 'c': 'S1',
+ 'b': 'b',
+ 'B': 'B',
+ 'h': 'h',
+ 'H': 'H',
+ 'i': 'i',
+ 'I': 'I',
+ 'l': 'l',
+ 'L': 'L',
+ 'q': 'q',
+ 'Q': 'Q',
+ 'e': 'e',
+ 'f': 'f',
+ 'd': 'd',
+ 'g': 'g',
+ 'Zf': 'F',
+ 'Zd': 'D',
+ 'Zg': 'G',
+ 's': 'S',
+ 'w': 'U',
+ 'O': 'O',
+ 'x': 'V', # padding
+}
+_pep3118_native_typechars = ''.join(_pep3118_native_map.keys())
+
+_pep3118_standard_map = {
+ '?': '?',
+ 'c': 'S1',
+ 'b': 'b',
+ 'B': 'B',
+ 'h': 'i2',
+ 'H': 'u2',
+ 'i': 'i4',
+ 'I': 'u4',
+ 'l': 'i4',
+ 'L': 'u4',
+ 'q': 'i8',
+ 'Q': 'u8',
+ 'e': 'f2',
+ 'f': 'f',
+ 'd': 'd',
+ 'Zf': 'F',
+ 'Zd': 'D',
+ 's': 'S',
+ 'w': 'U',
+ 'O': 'O',
+ 'x': 'V', # padding
+}
+_pep3118_standard_typechars = ''.join(_pep3118_standard_map.keys())
+
+_pep3118_unsupported_map = {
+ 'u': 'UCS-2 strings',
+ '&': 'pointers',
+ 't': 'bitfields',
+ 'X': 'function pointers',
+}
+
+class _Stream:
+ def __init__(self, s):
+ self.s = s
+ self.byteorder = '@'
+
+ def advance(self, n):
+ res = self.s[:n]
+ self.s = self.s[n:]
+ return res
+
+ def consume(self, c):
+ if self.s[:len(c)] == c:
+ self.advance(len(c))
+ return True
+ return False
+
+ def consume_until(self, c):
+ if callable(c):
+ i = 0
+ while i < len(self.s) and not c(self.s[i]):
+ i = i + 1
+ return self.advance(i)
+ else:
+ i = self.s.index(c)
+ res = self.advance(i)
+ self.advance(len(c))
+ return res
+
+ @property
+ def next(self):
+ return self.s[0]
+
+ def __bool__(self):
+ return bool(self.s)
+
+
+def _dtype_from_pep3118(spec):
+ stream = _Stream(spec)
+ dtype, align = __dtype_from_pep3118(stream, is_subdtype=False)
+ return dtype
+
+def __dtype_from_pep3118(stream, is_subdtype):
+ field_spec = dict(
+ names=[],
+ formats=[],
+ offsets=[],
+ itemsize=0
+ )
+ offset = 0
+ common_alignment = 1
+ is_padding = False
+
+ # Parse spec
+ while stream:
+ value = None
+
+ # End of structure, bail out to upper level
+ if stream.consume('}'):
+ break
+
+ # Sub-arrays (1)
+ shape = None
+ if stream.consume('('):
+ shape = stream.consume_until(')')
+ shape = tuple(map(int, shape.split(',')))
+
+ # Byte order
+ if stream.next in ('@', '=', '<', '>', '^', '!'):
+ byteorder = stream.advance(1)
+ if byteorder == '!':
+ byteorder = '>'
+ stream.byteorder = byteorder
+
+ # Byte order characters also control native vs. standard type sizes
+ if stream.byteorder in ('@', '^'):
+ type_map = _pep3118_native_map
+ type_map_chars = _pep3118_native_typechars
+ else:
+ type_map = _pep3118_standard_map
+ type_map_chars = _pep3118_standard_typechars
+
+ # Item sizes
+ itemsize_str = stream.consume_until(lambda c: not c.isdigit())
+ if itemsize_str:
+ itemsize = int(itemsize_str)
+ else:
+ itemsize = 1
+
+ # Data types
+ is_padding = False
+
+ if stream.consume('T{'):
+ value, align = __dtype_from_pep3118(
+ stream, is_subdtype=True)
+ elif stream.next in type_map_chars:
+ if stream.next == 'Z':
+ typechar = stream.advance(2)
+ else:
+ typechar = stream.advance(1)
+
+ is_padding = (typechar == 'x')
+ dtypechar = type_map[typechar]
+ if dtypechar in 'USV':
+ dtypechar += '%d' % itemsize
+ itemsize = 1
+ numpy_byteorder = {'@': '=', '^': '='}.get(
+ stream.byteorder, stream.byteorder)
+ value = dtype(numpy_byteorder + dtypechar)
+ align = value.alignment
+ elif stream.next in _pep3118_unsupported_map:
+ desc = _pep3118_unsupported_map[stream.next]
+ raise NotImplementedError(
+ "Unrepresentable PEP 3118 data type {!r} ({})"
+ .format(stream.next, desc))
+ else:
+ raise ValueError(
+ "Unknown PEP 3118 data type specifier %r" % stream.s
+ )
+
+ #
+ # Native alignment may require padding
+ #
+ # Here we assume that the presence of a '@' character implicitly
+ # implies that the start of the array is *already* aligned.
+ #
+ extra_offset = 0
+ if stream.byteorder == '@':
+ start_padding = (-offset) % align
+ intra_padding = (-value.itemsize) % align
+
+ offset += start_padding
+
+ if intra_padding != 0:
+ if itemsize > 1 or (shape is not None and _prod(shape) > 1):
+ # Inject internal padding to the end of the sub-item
+ value = _add_trailing_padding(value, intra_padding)
+ else:
+ # We can postpone the injection of internal padding,
+ # as the item appears at most once
+ extra_offset += intra_padding
+
+ # Update common alignment
+ common_alignment = _lcm(align, common_alignment)
+
+ # Convert itemsize to sub-array
+ if itemsize != 1:
+ value = dtype((value, (itemsize,)))
+
+ # Sub-arrays (2)
+ if shape is not None:
+ value = dtype((value, shape))
+
+ # Field name
+ if stream.consume(':'):
+ name = stream.consume_until(':')
+ else:
+ name = None
+
+ if not (is_padding and name is None):
+ if name is not None and name in field_spec['names']:
+ raise RuntimeError(
+ f"Duplicate field name '{name}' in PEP3118 format"
+ )
+ field_spec['names'].append(name)
+ field_spec['formats'].append(value)
+ field_spec['offsets'].append(offset)
+
+ offset += value.itemsize
+ offset += extra_offset
+
+ field_spec['itemsize'] = offset
+
+ # extra final padding for aligned types
+ if stream.byteorder == '@':
+ field_spec['itemsize'] += (-offset) % common_alignment
+
+ # Check if this was a simple 1-item type, and unwrap it
+ if (field_spec['names'] == [None]
+ and field_spec['offsets'][0] == 0
+ and field_spec['itemsize'] == field_spec['formats'][0].itemsize
+ and not is_subdtype):
+ ret = field_spec['formats'][0]
+ else:
+ _fix_names(field_spec)
+ ret = dtype(field_spec)
+
+ # Finished
+ return ret, common_alignment
+
+def _fix_names(field_spec):
+ """ Replace names which are None with the next unused f%d name """
+ names = field_spec['names']
+ for i, name in enumerate(names):
+ if name is not None:
+ continue
+
+ j = 0
+ while True:
+ name = f'f{j}'
+ if name not in names:
+ break
+ j = j + 1
+ names[i] = name
+
+def _add_trailing_padding(value, padding):
+ """Inject the specified number of padding bytes at the end of a dtype"""
+ if value.fields is None:
+ field_spec = dict(
+ names=['f0'],
+ formats=[value],
+ offsets=[0],
+ itemsize=value.itemsize
+ )
+ else:
+ fields = value.fields
+ names = value.names
+ field_spec = dict(
+ names=names,
+ formats=[fields[name][0] for name in names],
+ offsets=[fields[name][1] for name in names],
+ itemsize=value.itemsize
+ )
+
+ field_spec['itemsize'] += padding
+ return dtype(field_spec)
+
+def _prod(a):
+ p = 1
+ for x in a:
+ p *= x
+ return p
+
+def _gcd(a, b):
+ """Calculate the greatest common divisor of a and b"""
+ if not (math.isfinite(a) and math.isfinite(b)):
+ raise ValueError('Can only find greatest common divisor of '
+ f'finite arguments, found "{a}" and "{b}"')
+ while b:
+ a, b = b, a % b
+ return a
+
+def _lcm(a, b):
+ return a // _gcd(a, b) * b
+
+def array_ufunc_errmsg_formatter(dummy, ufunc, method, *inputs, **kwargs):
+ """ Format the error message for when __array_ufunc__ gives up. """
+ args_string = ', '.join(['{!r}'.format(arg) for arg in inputs] +
+ ['{}={!r}'.format(k, v)
+ for k, v in kwargs.items()])
+ args = inputs + kwargs.get('out', ())
+ types_string = ', '.join(repr(type(arg).__name__) for arg in args)
+ return ('operand type(s) all returned NotImplemented from '
+ '__array_ufunc__({!r}, {!r}, {}): {}'
+ .format(ufunc, method, args_string, types_string))
+
+
+def array_function_errmsg_formatter(public_api, types):
+ """ Format the error message for when __array_ufunc__ gives up. """
+ func_name = '{}.{}'.format(public_api.__module__, public_api.__name__)
+ return ("no implementation found for '{}' on types that implement "
+ '__array_function__: {}'.format(func_name, list(types)))
+
+
+def _ufunc_doc_signature_formatter(ufunc):
+ """
+ Builds a signature string which resembles PEP 457
+
+ This is used to construct the first line of the docstring
+ """
+
+ # input arguments are simple
+ if ufunc.nin == 1:
+ in_args = 'x'
+ else:
+ in_args = ', '.join(f'x{i+1}' for i in range(ufunc.nin))
+
+ # output arguments are both keyword or positional
+ if ufunc.nout == 0:
+ out_args = ', /, out=()'
+ elif ufunc.nout == 1:
+ out_args = ', /, out=None'
+ else:
+ out_args = '[, {positional}], / [, out={default}]'.format(
+ positional=', '.join(
+ 'out{}'.format(i+1) for i in range(ufunc.nout)),
+ default=repr((None,)*ufunc.nout)
+ )
+
+ # keyword only args depend on whether this is a gufunc
+ kwargs = (
+ ", casting='same_kind'"
+ ", order='K'"
+ ", dtype=None"
+ ", subok=True"
+ )
+
+ # NOTE: gufuncs may or may not support the `axis` parameter
+ if ufunc.signature is None:
+ kwargs = f", where=True{kwargs}[, signature]"
+ else:
+ kwargs += "[, signature, axes, axis]"
+
+ # join all the parts together
+ return '{name}({in_args}{out_args}, *{kwargs})'.format(
+ name=ufunc.__name__,
+ in_args=in_args,
+ out_args=out_args,
+ kwargs=kwargs
+ )
+
+
+def npy_ctypes_check(cls):
+ # determine if a class comes from ctypes, in order to work around
+ # a bug in the buffer protocol for those objects, bpo-10746
+ try:
+ # ctypes class are new-style, so have an __mro__. This probably fails
+ # for ctypes classes with multiple inheritance.
+ if IS_PYPY:
+ # (..., _ctypes.basics._CData, Bufferable, object)
+ ctype_base = cls.__mro__[-3]
+ else:
+ # # (..., _ctypes._CData, object)
+ ctype_base = cls.__mro__[-2]
+ # right now, they're part of the _ctypes module
+ return '_ctypes' in ctype_base.__module__
+ except Exception:
+ return False
+
+# used to handle the _NoValue default argument for na_object
+# in the C implementation of the __reduce__ method for stringdtype
+def _convert_to_stringdtype_kwargs(coerce, na_object=_NoValue):
+ if na_object is _NoValue:
+ return StringDType(coerce=coerce)
+ return StringDType(coerce=coerce, na_object=na_object)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_internal.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_internal.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..15726fe3064ec71c9f5f65211bcdad7a0f2ee646
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_internal.pyi
@@ -0,0 +1,72 @@
+import ctypes as ct
+import re
+from collections.abc import Callable, Iterable
+from typing import Any, Final, Generic, overload
+
+from typing_extensions import Self, TypeVar, deprecated
+
+import numpy as np
+import numpy.typing as npt
+from numpy.ctypeslib import c_intp
+
+_CastT = TypeVar("_CastT", bound=ct._CanCastTo)
+_T_co = TypeVar("_T_co", covariant=True)
+_CT = TypeVar("_CT", bound=ct._CData)
+_PT_co = TypeVar("_PT_co", bound=int | None, default=None, covariant=True)
+
+###
+
+IS_PYPY: Final[bool] = ...
+
+format_re: Final[re.Pattern[str]] = ...
+sep_re: Final[re.Pattern[str]] = ...
+space_re: Final[re.Pattern[str]] = ...
+
+###
+
+# TODO: Let the likes of `shape_as` and `strides_as` return `None`
+# for 0D arrays once we've got shape-support
+
+class _ctypes(Generic[_PT_co]):
+ @overload
+ def __init__(self: _ctypes[None], /, array: npt.NDArray[Any], ptr: None = None) -> None: ...
+ @overload
+ def __init__(self, /, array: npt.NDArray[Any], ptr: _PT_co) -> None: ...
+
+ #
+ @property
+ def data(self) -> _PT_co: ...
+ @property
+ def shape(self) -> ct.Array[c_intp]: ...
+ @property
+ def strides(self) -> ct.Array[c_intp]: ...
+ @property
+ def _as_parameter_(self) -> ct.c_void_p: ...
+
+ #
+ def data_as(self, /, obj: type[_CastT]) -> _CastT: ...
+ def shape_as(self, /, obj: type[_CT]) -> ct.Array[_CT]: ...
+ def strides_as(self, /, obj: type[_CT]) -> ct.Array[_CT]: ...
+
+ #
+ @deprecated('"get_data" is deprecated. Use "data" instead')
+ def get_data(self, /) -> _PT_co: ...
+ @deprecated('"get_shape" is deprecated. Use "shape" instead')
+ def get_shape(self, /) -> ct.Array[c_intp]: ...
+ @deprecated('"get_strides" is deprecated. Use "strides" instead')
+ def get_strides(self, /) -> ct.Array[c_intp]: ...
+ @deprecated('"get_as_parameter" is deprecated. Use "_as_parameter_" instead')
+ def get_as_parameter(self, /) -> ct.c_void_p: ...
+
+class dummy_ctype(Generic[_T_co]):
+ _cls: type[_T_co]
+
+ def __init__(self, /, cls: type[_T_co]) -> None: ...
+ def __eq__(self, other: Self, /) -> bool: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride]
+ def __ne__(self, other: Self, /) -> bool: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride]
+ def __mul__(self, other: object, /) -> Self: ...
+ def __call__(self, /, *other: object) -> _T_co: ...
+
+def array_ufunc_errmsg_formatter(dummy: object, ufunc: np.ufunc, method: str, *inputs: object, **kwargs: object) -> str: ...
+def array_function_errmsg_formatter(public_api: Callable[..., object], types: Iterable[str]) -> str: ...
+def npy_ctypes_check(cls: type) -> bool: ...
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_machar.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_machar.py
new file mode 100644
index 0000000000000000000000000000000000000000..d6e2d1496f28b785fda25a71b0552f0da80cdd3b
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_machar.py
@@ -0,0 +1,356 @@
+"""
+Machine arithmetic - determine the parameters of the
+floating-point arithmetic system
+
+Author: Pearu Peterson, September 2003
+
+"""
+__all__ = ['MachAr']
+
+from .fromnumeric import any
+from ._ufunc_config import errstate
+from .._utils import set_module
+
+# Need to speed this up...especially for longdouble
+
+# Deprecated 2021-10-20, NumPy 1.22
+class MachAr:
+ """
+ Diagnosing machine parameters.
+
+ Attributes
+ ----------
+ ibeta : int
+ Radix in which numbers are represented.
+ it : int
+ Number of base-`ibeta` digits in the floating point mantissa M.
+ machep : int
+ Exponent of the smallest (most negative) power of `ibeta` that,
+ added to 1.0, gives something different from 1.0
+ eps : float
+ Floating-point number ``beta**machep`` (floating point precision)
+ negep : int
+ Exponent of the smallest power of `ibeta` that, subtracted
+ from 1.0, gives something different from 1.0.
+ epsneg : float
+ Floating-point number ``beta**negep``.
+ iexp : int
+ Number of bits in the exponent (including its sign and bias).
+ minexp : int
+ Smallest (most negative) power of `ibeta` consistent with there
+ being no leading zeros in the mantissa.
+ xmin : float
+ Floating-point number ``beta**minexp`` (the smallest [in
+ magnitude] positive floating point number with full precision).
+ maxexp : int
+ Smallest (positive) power of `ibeta` that causes overflow.
+ xmax : float
+ ``(1-epsneg) * beta**maxexp`` (the largest [in magnitude]
+ usable floating value).
+ irnd : int
+ In ``range(6)``, information on what kind of rounding is done
+ in addition, and on how underflow is handled.
+ ngrd : int
+ Number of 'guard digits' used when truncating the product
+ of two mantissas to fit the representation.
+ epsilon : float
+ Same as `eps`.
+ tiny : float
+ An alias for `smallest_normal`, kept for backwards compatibility.
+ huge : float
+ Same as `xmax`.
+ precision : float
+ ``- int(-log10(eps))``
+ resolution : float
+ ``- 10**(-precision)``
+ smallest_normal : float
+ The smallest positive floating point number with 1 as leading bit in
+ the mantissa following IEEE-754. Same as `xmin`.
+ smallest_subnormal : float
+ The smallest positive floating point number with 0 as leading bit in
+ the mantissa following IEEE-754.
+
+ Parameters
+ ----------
+ float_conv : function, optional
+ Function that converts an integer or integer array to a float
+ or float array. Default is `float`.
+ int_conv : function, optional
+ Function that converts a float or float array to an integer or
+ integer array. Default is `int`.
+ float_to_float : function, optional
+ Function that converts a float array to float. Default is `float`.
+ Note that this does not seem to do anything useful in the current
+ implementation.
+ float_to_str : function, optional
+ Function that converts a single float to a string. Default is
+ ``lambda v:'%24.16e' %v``.
+ title : str, optional
+ Title that is printed in the string representation of `MachAr`.
+
+ See Also
+ --------
+ finfo : Machine limits for floating point types.
+ iinfo : Machine limits for integer types.
+
+ References
+ ----------
+ .. [1] Press, Teukolsky, Vetterling and Flannery,
+ "Numerical Recipes in C++," 2nd ed,
+ Cambridge University Press, 2002, p. 31.
+
+ """
+
+ def __init__(self, float_conv=float,int_conv=int,
+ float_to_float=float,
+ float_to_str=lambda v:'%24.16e' % v,
+ title='Python floating point number'):
+ """
+
+ float_conv - convert integer to float (array)
+ int_conv - convert float (array) to integer
+ float_to_float - convert float array to float
+ float_to_str - convert array float to str
+ title - description of used floating point numbers
+
+ """
+ # We ignore all errors here because we are purposely triggering
+ # underflow to detect the properties of the running arch.
+ with errstate(under='ignore'):
+ self._do_init(float_conv, int_conv, float_to_float, float_to_str, title)
+
+ def _do_init(self, float_conv, int_conv, float_to_float, float_to_str, title):
+ max_iterN = 10000
+ msg = "Did not converge after %d tries with %s"
+ one = float_conv(1)
+ two = one + one
+ zero = one - one
+
+ # Do we really need to do this? Aren't they 2 and 2.0?
+ # Determine ibeta and beta
+ a = one
+ for _ in range(max_iterN):
+ a = a + a
+ temp = a + one
+ temp1 = temp - a
+ if any(temp1 - one != zero):
+ break
+ else:
+ raise RuntimeError(msg % (_, one.dtype))
+ b = one
+ for _ in range(max_iterN):
+ b = b + b
+ temp = a + b
+ itemp = int_conv(temp-a)
+ if any(itemp != 0):
+ break
+ else:
+ raise RuntimeError(msg % (_, one.dtype))
+ ibeta = itemp
+ beta = float_conv(ibeta)
+
+ # Determine it and irnd
+ it = -1
+ b = one
+ for _ in range(max_iterN):
+ it = it + 1
+ b = b * beta
+ temp = b + one
+ temp1 = temp - b
+ if any(temp1 - one != zero):
+ break
+ else:
+ raise RuntimeError(msg % (_, one.dtype))
+
+ betah = beta / two
+ a = one
+ for _ in range(max_iterN):
+ a = a + a
+ temp = a + one
+ temp1 = temp - a
+ if any(temp1 - one != zero):
+ break
+ else:
+ raise RuntimeError(msg % (_, one.dtype))
+ temp = a + betah
+ irnd = 0
+ if any(temp-a != zero):
+ irnd = 1
+ tempa = a + beta
+ temp = tempa + betah
+ if irnd == 0 and any(temp-tempa != zero):
+ irnd = 2
+
+ # Determine negep and epsneg
+ negep = it + 3
+ betain = one / beta
+ a = one
+ for i in range(negep):
+ a = a * betain
+ b = a
+ for _ in range(max_iterN):
+ temp = one - a
+ if any(temp-one != zero):
+ break
+ a = a * beta
+ negep = negep - 1
+ # Prevent infinite loop on PPC with gcc 4.0:
+ if negep < 0:
+ raise RuntimeError("could not determine machine tolerance "
+ "for 'negep', locals() -> %s" % (locals()))
+ else:
+ raise RuntimeError(msg % (_, one.dtype))
+ negep = -negep
+ epsneg = a
+
+ # Determine machep and eps
+ machep = - it - 3
+ a = b
+
+ for _ in range(max_iterN):
+ temp = one + a
+ if any(temp-one != zero):
+ break
+ a = a * beta
+ machep = machep + 1
+ else:
+ raise RuntimeError(msg % (_, one.dtype))
+ eps = a
+
+ # Determine ngrd
+ ngrd = 0
+ temp = one + eps
+ if irnd == 0 and any(temp*one - one != zero):
+ ngrd = 1
+
+ # Determine iexp
+ i = 0
+ k = 1
+ z = betain
+ t = one + eps
+ nxres = 0
+ for _ in range(max_iterN):
+ y = z
+ z = y*y
+ a = z*one # Check here for underflow
+ temp = z*t
+ if any(a+a == zero) or any(abs(z) >= y):
+ break
+ temp1 = temp * betain
+ if any(temp1*beta == z):
+ break
+ i = i + 1
+ k = k + k
+ else:
+ raise RuntimeError(msg % (_, one.dtype))
+ if ibeta != 10:
+ iexp = i + 1
+ mx = k + k
+ else:
+ iexp = 2
+ iz = ibeta
+ while k >= iz:
+ iz = iz * ibeta
+ iexp = iexp + 1
+ mx = iz + iz - 1
+
+ # Determine minexp and xmin
+ for _ in range(max_iterN):
+ xmin = y
+ y = y * betain
+ a = y * one
+ temp = y * t
+ if any((a + a) != zero) and any(abs(y) < xmin):
+ k = k + 1
+ temp1 = temp * betain
+ if any(temp1*beta == y) and any(temp != y):
+ nxres = 3
+ xmin = y
+ break
+ else:
+ break
+ else:
+ raise RuntimeError(msg % (_, one.dtype))
+ minexp = -k
+
+ # Determine maxexp, xmax
+ if mx <= k + k - 3 and ibeta != 10:
+ mx = mx + mx
+ iexp = iexp + 1
+ maxexp = mx + minexp
+ irnd = irnd + nxres
+ if irnd >= 2:
+ maxexp = maxexp - 2
+ i = maxexp + minexp
+ if ibeta == 2 and not i:
+ maxexp = maxexp - 1
+ if i > 20:
+ maxexp = maxexp - 1
+ if any(a != y):
+ maxexp = maxexp - 2
+ xmax = one - epsneg
+ if any(xmax*one != xmax):
+ xmax = one - beta*epsneg
+ xmax = xmax / (xmin*beta*beta*beta)
+ i = maxexp + minexp + 3
+ for j in range(i):
+ if ibeta == 2:
+ xmax = xmax + xmax
+ else:
+ xmax = xmax * beta
+
+ smallest_subnormal = abs(xmin / beta ** (it))
+
+ self.ibeta = ibeta
+ self.it = it
+ self.negep = negep
+ self.epsneg = float_to_float(epsneg)
+ self._str_epsneg = float_to_str(epsneg)
+ self.machep = machep
+ self.eps = float_to_float(eps)
+ self._str_eps = float_to_str(eps)
+ self.ngrd = ngrd
+ self.iexp = iexp
+ self.minexp = minexp
+ self.xmin = float_to_float(xmin)
+ self._str_xmin = float_to_str(xmin)
+ self.maxexp = maxexp
+ self.xmax = float_to_float(xmax)
+ self._str_xmax = float_to_str(xmax)
+ self.irnd = irnd
+
+ self.title = title
+ # Commonly used parameters
+ self.epsilon = self.eps
+ self.tiny = self.xmin
+ self.huge = self.xmax
+ self.smallest_normal = self.xmin
+ self._str_smallest_normal = float_to_str(self.xmin)
+ self.smallest_subnormal = float_to_float(smallest_subnormal)
+ self._str_smallest_subnormal = float_to_str(smallest_subnormal)
+
+ import math
+ self.precision = int(-math.log10(float_to_float(self.eps)))
+ ten = two + two + two + two + two
+ resolution = ten ** (-self.precision)
+ self.resolution = float_to_float(resolution)
+ self._str_resolution = float_to_str(resolution)
+
+ def __str__(self):
+ fmt = (
+ 'Machine parameters for %(title)s\n'
+ '---------------------------------------------------------------------\n'
+ 'ibeta=%(ibeta)s it=%(it)s iexp=%(iexp)s ngrd=%(ngrd)s irnd=%(irnd)s\n'
+ 'machep=%(machep)s eps=%(_str_eps)s (beta**machep == epsilon)\n'
+ 'negep =%(negep)s epsneg=%(_str_epsneg)s (beta**epsneg)\n'
+ 'minexp=%(minexp)s xmin=%(_str_xmin)s (beta**minexp == tiny)\n'
+ 'maxexp=%(maxexp)s xmax=%(_str_xmax)s ((1-epsneg)*beta**maxexp == huge)\n'
+ 'smallest_normal=%(smallest_normal)s '
+ 'smallest_subnormal=%(smallest_subnormal)s\n'
+ '---------------------------------------------------------------------\n'
+ )
+ return fmt % self.__dict__
+
+
+if __name__ == '__main__':
+ print(MachAr())
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_machar.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_machar.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..5abfc779c2120734c29d017844dd6ecc2b171bdb
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_machar.pyi
@@ -0,0 +1,73 @@
+from collections.abc import Iterable
+from typing import Any, Final, overload
+
+from typing_extensions import TypeVar, Unpack
+
+import numpy as np
+from numpy import _CastingKind
+from numpy._utils import set_module as set_module
+
+###
+
+_T = TypeVar("_T")
+_TupleT = TypeVar("_TupleT", bound=tuple[()] | tuple[Any, Any, Unpack[tuple[Any, ...]]])
+_ExceptionT = TypeVar("_ExceptionT", bound=Exception)
+
+###
+
+class UFuncTypeError(TypeError):
+ ufunc: Final[np.ufunc]
+ def __init__(self, /, ufunc: np.ufunc) -> None: ...
+
+class _UFuncNoLoopError(UFuncTypeError):
+ dtypes: tuple[np.dtype[Any], ...]
+ def __init__(self, /, ufunc: np.ufunc, dtypes: Iterable[np.dtype[Any]]) -> None: ...
+
+class _UFuncBinaryResolutionError(_UFuncNoLoopError):
+ dtypes: tuple[np.dtype[Any], np.dtype[Any]]
+ def __init__(self, /, ufunc: np.ufunc, dtypes: Iterable[np.dtype[Any]]) -> None: ...
+
+class _UFuncCastingError(UFuncTypeError):
+ casting: Final[_CastingKind]
+ from_: Final[np.dtype[Any]]
+ to: Final[np.dtype[Any]]
+ def __init__(self, /, ufunc: np.ufunc, casting: _CastingKind, from_: np.dtype[Any], to: np.dtype[Any]) -> None: ...
+
+class _UFuncInputCastingError(_UFuncCastingError):
+ in_i: Final[int]
+ def __init__(
+ self,
+ /,
+ ufunc: np.ufunc,
+ casting: _CastingKind,
+ from_: np.dtype[Any],
+ to: np.dtype[Any],
+ i: int,
+ ) -> None: ...
+
+class _UFuncOutputCastingError(_UFuncCastingError):
+ out_i: Final[int]
+ def __init__(
+ self,
+ /,
+ ufunc: np.ufunc,
+ casting: _CastingKind,
+ from_: np.dtype[Any],
+ to: np.dtype[Any],
+ i: int,
+ ) -> None: ...
+
+class _ArrayMemoryError(MemoryError):
+ shape: tuple[int, ...]
+ dtype: np.dtype[Any]
+ def __init__(self, /, shape: tuple[int, ...], dtype: np.dtype[Any]) -> None: ...
+ @property
+ def _total_size(self) -> int: ...
+ @staticmethod
+ def _size_to_string(num_bytes: int) -> str: ...
+
+@overload
+def _unpack_tuple(tup: tuple[_T]) -> _T: ...
+@overload
+def _unpack_tuple(tup: _TupleT) -> _TupleT: ...
+def _display_as_base(cls: type[_ExceptionT]) -> type[_ExceptionT]: ...
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_methods.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_methods.py
new file mode 100644
index 0000000000000000000000000000000000000000..03c673fc0ff881d8de7f5d6f52abf975c9db3360
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_methods.py
@@ -0,0 +1,256 @@
+"""
+Array methods which are called by both the C-code for the method
+and the Python code for the NumPy-namespace function
+
+"""
+import os
+import pickle
+import warnings
+from contextlib import nullcontext
+
+import numpy as np
+from numpy._core import multiarray as mu
+from numpy._core import umath as um
+from numpy._core.multiarray import asanyarray
+from numpy._core import numerictypes as nt
+from numpy._core import _exceptions
+from numpy._globals import _NoValue
+
+# save those O(100) nanoseconds!
+bool_dt = mu.dtype("bool")
+umr_maximum = um.maximum.reduce
+umr_minimum = um.minimum.reduce
+umr_sum = um.add.reduce
+umr_prod = um.multiply.reduce
+umr_bitwise_count = um.bitwise_count
+umr_any = um.logical_or.reduce
+umr_all = um.logical_and.reduce
+
+# Complex types to -> (2,)float view for fast-path computation in _var()
+_complex_to_float = {
+ nt.dtype(nt.csingle) : nt.dtype(nt.single),
+ nt.dtype(nt.cdouble) : nt.dtype(nt.double),
+}
+# Special case for windows: ensure double takes precedence
+if nt.dtype(nt.longdouble) != nt.dtype(nt.double):
+ _complex_to_float.update({
+ nt.dtype(nt.clongdouble) : nt.dtype(nt.longdouble),
+ })
+
+# avoid keyword arguments to speed up parsing, saves about 15%-20% for very
+# small reductions
+def _amax(a, axis=None, out=None, keepdims=False,
+ initial=_NoValue, where=True):
+ return umr_maximum(a, axis, None, out, keepdims, initial, where)
+
+def _amin(a, axis=None, out=None, keepdims=False,
+ initial=_NoValue, where=True):
+ return umr_minimum(a, axis, None, out, keepdims, initial, where)
+
+def _sum(a, axis=None, dtype=None, out=None, keepdims=False,
+ initial=_NoValue, where=True):
+ return umr_sum(a, axis, dtype, out, keepdims, initial, where)
+
+def _prod(a, axis=None, dtype=None, out=None, keepdims=False,
+ initial=_NoValue, where=True):
+ return umr_prod(a, axis, dtype, out, keepdims, initial, where)
+
+def _any(a, axis=None, dtype=None, out=None, keepdims=False, *, where=True):
+ # By default, return a boolean for any and all
+ if dtype is None:
+ dtype = bool_dt
+ # Parsing keyword arguments is currently fairly slow, so avoid it for now
+ if where is True:
+ return umr_any(a, axis, dtype, out, keepdims)
+ return umr_any(a, axis, dtype, out, keepdims, where=where)
+
+def _all(a, axis=None, dtype=None, out=None, keepdims=False, *, where=True):
+ # By default, return a boolean for any and all
+ if dtype is None:
+ dtype = bool_dt
+ # Parsing keyword arguments is currently fairly slow, so avoid it for now
+ if where is True:
+ return umr_all(a, axis, dtype, out, keepdims)
+ return umr_all(a, axis, dtype, out, keepdims, where=where)
+
+def _count_reduce_items(arr, axis, keepdims=False, where=True):
+ # fast-path for the default case
+ if where is True:
+ # no boolean mask given, calculate items according to axis
+ if axis is None:
+ axis = tuple(range(arr.ndim))
+ elif not isinstance(axis, tuple):
+ axis = (axis,)
+ items = 1
+ for ax in axis:
+ items *= arr.shape[mu.normalize_axis_index(ax, arr.ndim)]
+ items = nt.intp(items)
+ else:
+ # TODO: Optimize case when `where` is broadcast along a non-reduction
+ # axis and full sum is more excessive than needed.
+
+ # guarded to protect circular imports
+ from numpy.lib._stride_tricks_impl import broadcast_to
+ # count True values in (potentially broadcasted) boolean mask
+ items = umr_sum(broadcast_to(where, arr.shape), axis, nt.intp, None,
+ keepdims)
+ return items
+
+def _clip(a, min=None, max=None, out=None, **kwargs):
+ if a.dtype.kind in "iu":
+ # If min/max is a Python integer, deal with out-of-bound values here.
+ # (This enforces NEP 50 rules as no value based promotion is done.)
+ if type(min) is int and min <= np.iinfo(a.dtype).min:
+ min = None
+ if type(max) is int and max >= np.iinfo(a.dtype).max:
+ max = None
+
+ if min is None and max is None:
+ # return identity
+ return um.positive(a, out=out, **kwargs)
+ elif min is None:
+ return um.minimum(a, max, out=out, **kwargs)
+ elif max is None:
+ return um.maximum(a, min, out=out, **kwargs)
+ else:
+ return um.clip(a, min, max, out=out, **kwargs)
+
+def _mean(a, axis=None, dtype=None, out=None, keepdims=False, *, where=True):
+ arr = asanyarray(a)
+
+ is_float16_result = False
+
+ rcount = _count_reduce_items(arr, axis, keepdims=keepdims, where=where)
+ if rcount == 0 if where is True else umr_any(rcount == 0, axis=None):
+ warnings.warn("Mean of empty slice.", RuntimeWarning, stacklevel=2)
+
+ # Cast bool, unsigned int, and int to float64 by default
+ if dtype is None:
+ if issubclass(arr.dtype.type, (nt.integer, nt.bool)):
+ dtype = mu.dtype('f8')
+ elif issubclass(arr.dtype.type, nt.float16):
+ dtype = mu.dtype('f4')
+ is_float16_result = True
+
+ ret = umr_sum(arr, axis, dtype, out, keepdims, where=where)
+ if isinstance(ret, mu.ndarray):
+ ret = um.true_divide(
+ ret, rcount, out=ret, casting='unsafe', subok=False)
+ if is_float16_result and out is None:
+ ret = arr.dtype.type(ret)
+ elif hasattr(ret, 'dtype'):
+ if is_float16_result:
+ ret = arr.dtype.type(ret / rcount)
+ else:
+ ret = ret.dtype.type(ret / rcount)
+ else:
+ ret = ret / rcount
+
+ return ret
+
+def _var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False, *,
+ where=True, mean=None):
+ arr = asanyarray(a)
+
+ rcount = _count_reduce_items(arr, axis, keepdims=keepdims, where=where)
+ # Make this warning show up on top.
+ if ddof >= rcount if where is True else umr_any(ddof >= rcount, axis=None):
+ warnings.warn("Degrees of freedom <= 0 for slice", RuntimeWarning,
+ stacklevel=2)
+
+ # Cast bool, unsigned int, and int to float64 by default
+ if dtype is None and issubclass(arr.dtype.type, (nt.integer, nt.bool)):
+ dtype = mu.dtype('f8')
+
+ if mean is not None:
+ arrmean = mean
+ else:
+ # Compute the mean.
+ # Note that if dtype is not of inexact type then arraymean will
+ # not be either.
+ arrmean = umr_sum(arr, axis, dtype, keepdims=True, where=where)
+ # The shape of rcount has to match arrmean to not change the shape of
+ # out in broadcasting. Otherwise, it cannot be stored back to arrmean.
+ if rcount.ndim == 0:
+ # fast-path for default case when where is True
+ div = rcount
+ else:
+ # matching rcount to arrmean when where is specified as array
+ div = rcount.reshape(arrmean.shape)
+ if isinstance(arrmean, mu.ndarray):
+ arrmean = um.true_divide(arrmean, div, out=arrmean,
+ casting='unsafe', subok=False)
+ elif hasattr(arrmean, "dtype"):
+ arrmean = arrmean.dtype.type(arrmean / rcount)
+ else:
+ arrmean = arrmean / rcount
+
+ # Compute sum of squared deviations from mean
+ # Note that x may not be inexact and that we need it to be an array,
+ # not a scalar.
+ x = asanyarray(arr - arrmean)
+
+ if issubclass(arr.dtype.type, (nt.floating, nt.integer)):
+ x = um.multiply(x, x, out=x)
+ # Fast-paths for built-in complex types
+ elif x.dtype in _complex_to_float:
+ xv = x.view(dtype=(_complex_to_float[x.dtype], (2,)))
+ um.multiply(xv, xv, out=xv)
+ x = um.add(xv[..., 0], xv[..., 1], out=x.real).real
+ # Most general case; includes handling object arrays containing imaginary
+ # numbers and complex types with non-native byteorder
+ else:
+ x = um.multiply(x, um.conjugate(x), out=x).real
+
+ ret = umr_sum(x, axis, dtype, out, keepdims=keepdims, where=where)
+
+ # Compute degrees of freedom and make sure it is not negative.
+ rcount = um.maximum(rcount - ddof, 0)
+
+ # divide by degrees of freedom
+ if isinstance(ret, mu.ndarray):
+ ret = um.true_divide(
+ ret, rcount, out=ret, casting='unsafe', subok=False)
+ elif hasattr(ret, 'dtype'):
+ ret = ret.dtype.type(ret / rcount)
+ else:
+ ret = ret / rcount
+
+ return ret
+
+def _std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False, *,
+ where=True, mean=None):
+ ret = _var(a, axis=axis, dtype=dtype, out=out, ddof=ddof,
+ keepdims=keepdims, where=where, mean=mean)
+
+ if isinstance(ret, mu.ndarray):
+ ret = um.sqrt(ret, out=ret)
+ elif hasattr(ret, 'dtype'):
+ ret = ret.dtype.type(um.sqrt(ret))
+ else:
+ ret = um.sqrt(ret)
+
+ return ret
+
+def _ptp(a, axis=None, out=None, keepdims=False):
+ return um.subtract(
+ umr_maximum(a, axis, None, out, keepdims),
+ umr_minimum(a, axis, None, None, keepdims),
+ out
+ )
+
+def _dump(self, file, protocol=2):
+ if hasattr(file, 'write'):
+ ctx = nullcontext(file)
+ else:
+ ctx = open(os.fspath(file), "wb")
+ with ctx as f:
+ pickle.dump(self, f, protocol=protocol)
+
+def _dumps(self, protocol=2):
+ return pickle.dumps(self, protocol=protocol)
+
+def _bitwise_count(a, out=None, *, where=True, casting='same_kind',
+ order='K', dtype=None, subok=True):
+ return umr_bitwise_count(a, out, where=where, casting=casting,
+ order=order, dtype=dtype, subok=subok)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_methods.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_methods.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..45e2b8b9f761d9144fbc054a8f461d557a3f7690
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_methods.pyi
@@ -0,0 +1,24 @@
+from collections.abc import Callable
+from typing import Any, TypeAlias
+
+from typing_extensions import Concatenate
+
+import numpy as np
+
+from . import _exceptions as _exceptions
+
+###
+
+_Reduce2: TypeAlias = Callable[Concatenate[object, ...], Any]
+
+###
+
+bool_dt: np.dtype[np.bool] = ...
+umr_maximum: _Reduce2 = ...
+umr_minimum: _Reduce2 = ...
+umr_sum: _Reduce2 = ...
+umr_prod: _Reduce2 = ...
+umr_bitwise_count = np.bitwise_count
+umr_any: _Reduce2 = ...
+umr_all: _Reduce2 = ...
+_complex_to_float: dict[np.dtype[np.complexfloating], np.dtype[np.floating]] = ...
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_operand_flag_tests.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_operand_flag_tests.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..d59f49e9b59fa7f7099de3a42f9dc3f64689180f
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_operand_flag_tests.cpython-310-x86_64-linux-gnu.so differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_rational_tests.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_rational_tests.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..c1d1743efb448697e4b7aa3a0373579f73c55f65
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_rational_tests.cpython-310-x86_64-linux-gnu.so differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_simd.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_simd.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..70bb7077797e044f6214a731642cc815bf63868d
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_simd.pyi
@@ -0,0 +1,25 @@
+from types import ModuleType
+from typing import TypedDict, type_check_only
+
+# NOTE: these 5 are only defined on systems with an intel processor
+SSE42: ModuleType | None = ...
+FMA3: ModuleType | None = ...
+AVX2: ModuleType | None = ...
+AVX512F: ModuleType | None = ...
+AVX512_SKX: ModuleType | None = ...
+
+baseline: ModuleType | None = ...
+
+@type_check_only
+class SimdTargets(TypedDict):
+ SSE42: ModuleType | None
+ AVX2: ModuleType | None
+ FMA3: ModuleType | None
+ AVX512F: ModuleType | None
+ AVX512_SKX: ModuleType | None
+ baseline: ModuleType | None
+
+targets: SimdTargets = ...
+
+def clear_floatstatus() -> None: ...
+def get_floatstatus() -> int: ...
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_string_helpers.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_string_helpers.py
new file mode 100644
index 0000000000000000000000000000000000000000..8a64ab5a05e43714d07245b3ad7cd204e1831095
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_string_helpers.py
@@ -0,0 +1,100 @@
+"""
+String-handling utilities to avoid locale-dependence.
+
+Used primarily to generate type name aliases.
+"""
+# "import string" is costly to import!
+# Construct the translation tables directly
+# "A" = chr(65), "a" = chr(97)
+_all_chars = tuple(map(chr, range(256)))
+_ascii_upper = _all_chars[65:65+26]
+_ascii_lower = _all_chars[97:97+26]
+LOWER_TABLE = _all_chars[:65] + _ascii_lower + _all_chars[65+26:]
+UPPER_TABLE = _all_chars[:97] + _ascii_upper + _all_chars[97+26:]
+
+
+def english_lower(s):
+ """ Apply English case rules to convert ASCII strings to all lower case.
+
+ This is an internal utility function to replace calls to str.lower() such
+ that we can avoid changing behavior with changing locales. In particular,
+ Turkish has distinct dotted and dotless variants of the Latin letter "I" in
+ both lowercase and uppercase. Thus, "I".lower() != "i" in a "tr" locale.
+
+ Parameters
+ ----------
+ s : str
+
+ Returns
+ -------
+ lowered : str
+
+ Examples
+ --------
+ >>> from numpy._core.numerictypes import english_lower
+ >>> english_lower('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_')
+ 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789_'
+ >>> english_lower('')
+ ''
+ """
+ lowered = s.translate(LOWER_TABLE)
+ return lowered
+
+
+def english_upper(s):
+ """ Apply English case rules to convert ASCII strings to all upper case.
+
+ This is an internal utility function to replace calls to str.upper() such
+ that we can avoid changing behavior with changing locales. In particular,
+ Turkish has distinct dotted and dotless variants of the Latin letter "I" in
+ both lowercase and uppercase. Thus, "i".upper() != "I" in a "tr" locale.
+
+ Parameters
+ ----------
+ s : str
+
+ Returns
+ -------
+ uppered : str
+
+ Examples
+ --------
+ >>> from numpy._core.numerictypes import english_upper
+ >>> english_upper('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_')
+ 'ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_'
+ >>> english_upper('')
+ ''
+ """
+ uppered = s.translate(UPPER_TABLE)
+ return uppered
+
+
+def english_capitalize(s):
+ """ Apply English case rules to convert the first character of an ASCII
+ string to upper case.
+
+ This is an internal utility function to replace calls to str.capitalize()
+ such that we can avoid changing behavior with changing locales.
+
+ Parameters
+ ----------
+ s : str
+
+ Returns
+ -------
+ capitalized : str
+
+ Examples
+ --------
+ >>> from numpy._core.numerictypes import english_capitalize
+ >>> english_capitalize('int8')
+ 'Int8'
+ >>> english_capitalize('Int8')
+ 'Int8'
+ >>> english_capitalize('')
+ ''
+ """
+ if s:
+ return english_upper(s[0]) + s[1:]
+ else:
+ return s
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_string_helpers.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_string_helpers.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..6a85832b7a930edf28cf414e1f7801e6a3d94605
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_string_helpers.pyi
@@ -0,0 +1,12 @@
+from typing import Final
+
+_all_chars: Final[tuple[str, ...]] = ...
+_ascii_upper: Final[tuple[str, ...]] = ...
+_ascii_lower: Final[tuple[str, ...]] = ...
+
+LOWER_TABLE: Final[tuple[str, ...]] = ...
+UPPER_TABLE: Final[tuple[str, ...]] = ...
+
+def english_lower(s: str) -> str: ...
+def english_upper(s: str) -> str: ...
+def english_capitalize(s: str) -> str: ...
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_struct_ufunc_tests.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_struct_ufunc_tests.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..13a0f4984c3f15de34d6285a34f2ec84c455b58c
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_struct_ufunc_tests.cpython-310-x86_64-linux-gnu.so differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_type_aliases.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_type_aliases.py
new file mode 100644
index 0000000000000000000000000000000000000000..b8ea3851f0e5c4375b272925f375752a34118a24
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_type_aliases.py
@@ -0,0 +1,119 @@
+"""
+Due to compatibility, numpy has a very large number of different naming
+conventions for the scalar types (those subclassing from `numpy.generic`).
+This file produces a convoluted set of dictionaries mapping names to types,
+and sometimes other mappings too.
+
+.. data:: allTypes
+ A dictionary of names to types that will be exposed as attributes through
+ ``np._core.numerictypes.*``
+
+.. data:: sctypeDict
+ Similar to `allTypes`, but maps a broader set of aliases to their types.
+
+.. data:: sctypes
+ A dictionary keyed by a "type group" string, providing a list of types
+ under that group.
+
+"""
+
+import numpy._core.multiarray as ma
+from numpy._core.multiarray import typeinfo, dtype
+
+######################################
+# Building `sctypeDict` and `allTypes`
+######################################
+
+sctypeDict = {}
+allTypes = {}
+c_names_dict = {}
+
+_abstract_type_names = {
+ "generic", "integer", "inexact", "floating", "number",
+ "flexible", "character", "complexfloating", "unsignedinteger",
+ "signedinteger"
+}
+
+for _abstract_type_name in _abstract_type_names:
+ allTypes[_abstract_type_name] = getattr(ma, _abstract_type_name)
+
+for k, v in typeinfo.items():
+ if k.startswith("NPY_") and v not in c_names_dict:
+ c_names_dict[k[4:]] = v
+ else:
+ concrete_type = v.type
+ allTypes[k] = concrete_type
+ sctypeDict[k] = concrete_type
+
+_aliases = {
+ "double": "float64",
+ "cdouble": "complex128",
+ "single": "float32",
+ "csingle": "complex64",
+ "half": "float16",
+ "bool_": "bool",
+ # Default integer:
+ "int_": "intp",
+ "uint": "uintp",
+}
+
+for k, v in _aliases.items():
+ sctypeDict[k] = allTypes[v]
+ allTypes[k] = allTypes[v]
+
+# extra aliases are added only to `sctypeDict`
+# to support dtype name access, such as`np.dtype("float")`
+_extra_aliases = {
+ "float": "float64",
+ "complex": "complex128",
+ "object": "object_",
+ "bytes": "bytes_",
+ "a": "bytes_",
+ "int": "int_",
+ "str": "str_",
+ "unicode": "str_",
+}
+
+for k, v in _extra_aliases.items():
+ sctypeDict[k] = allTypes[v]
+
+# include extended precision sized aliases
+for is_complex, full_name in [(False, "longdouble"), (True, "clongdouble")]:
+ longdouble_type: type = allTypes[full_name]
+
+ bits: int = dtype(longdouble_type).itemsize * 8
+ base_name: str = "complex" if is_complex else "float"
+ extended_prec_name: str = f"{base_name}{bits}"
+ if extended_prec_name not in allTypes:
+ sctypeDict[extended_prec_name] = longdouble_type
+ allTypes[extended_prec_name] = longdouble_type
+
+
+####################
+# Building `sctypes`
+####################
+
+sctypes = {"int": set(), "uint": set(), "float": set(),
+ "complex": set(), "others": set()}
+
+for type_info in typeinfo.values():
+ if type_info.kind in ["M", "m"]: # exclude timedelta and datetime
+ continue
+
+ concrete_type = type_info.type
+
+ # find proper group for each concrete type
+ for type_group, abstract_type in [
+ ("int", ma.signedinteger), ("uint", ma.unsignedinteger),
+ ("float", ma.floating), ("complex", ma.complexfloating),
+ ("others", ma.generic)
+ ]:
+ if issubclass(concrete_type, abstract_type):
+ sctypes[type_group].add(concrete_type)
+ break
+
+# sort sctype groups by bitsize
+for sctype_key in sctypes.keys():
+ sctype_list = list(sctypes[sctype_key])
+ sctype_list.sort(key=lambda x: dtype(x).itemsize)
+ sctypes[sctype_key] = sctype_list
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_type_aliases.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_type_aliases.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..f92958a67d55a04e9bb66c4cf5aeefdf7aa2650d
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_type_aliases.pyi
@@ -0,0 +1,96 @@
+from collections.abc import Collection
+from typing import Any, Final, Literal as L, TypeAlias, TypedDict, type_check_only
+
+import numpy as np
+
+__all__ = (
+ "_abstract_type_names",
+ "_aliases",
+ "_extra_aliases",
+ "allTypes",
+ "c_names_dict",
+ "sctypeDict",
+ "sctypes",
+)
+
+sctypeDict: Final[dict[str, type[np.generic]]]
+allTypes: Final[dict[str, type[np.generic]]]
+
+@type_check_only
+class _CNamesDict(TypedDict):
+ BOOL: np.dtype[np.bool]
+ HALF: np.dtype[np.half]
+ FLOAT: np.dtype[np.single]
+ DOUBLE: np.dtype[np.double]
+ LONGDOUBLE: np.dtype[np.longdouble]
+ CFLOAT: np.dtype[np.csingle]
+ CDOUBLE: np.dtype[np.cdouble]
+ CLONGDOUBLE: np.dtype[np.clongdouble]
+ STRING: np.dtype[np.bytes_]
+ UNICODE: np.dtype[np.str_]
+ VOID: np.dtype[np.void]
+ OBJECT: np.dtype[np.object_]
+ DATETIME: np.dtype[np.datetime64]
+ TIMEDELTA: np.dtype[np.timedelta64]
+ BYTE: np.dtype[np.byte]
+ UBYTE: np.dtype[np.ubyte]
+ SHORT: np.dtype[np.short]
+ USHORT: np.dtype[np.ushort]
+ INT: np.dtype[np.intc]
+ UINT: np.dtype[np.uintc]
+ LONG: np.dtype[np.long]
+ ULONG: np.dtype[np.ulong]
+ LONGLONG: np.dtype[np.longlong]
+ ULONGLONG: np.dtype[np.ulonglong]
+
+c_names_dict: Final[_CNamesDict]
+
+_AbstractTypeName: TypeAlias = L[
+ "generic",
+ "flexible",
+ "character",
+ "number",
+ "integer",
+ "inexact",
+ "unsignedinteger",
+ "signedinteger",
+ "floating",
+ "complexfloating",
+]
+_abstract_type_names: Final[set[_AbstractTypeName]]
+
+@type_check_only
+class _AliasesType(TypedDict):
+ double: L["float64"]
+ cdouble: L["complex128"]
+ single: L["float32"]
+ csingle: L["complex64"]
+ half: L["float16"]
+ bool_: L["bool"]
+ int_: L["intp"]
+ uint: L["intp"]
+
+_aliases: Final[_AliasesType]
+
+@type_check_only
+class _ExtraAliasesType(TypedDict):
+ float: L["float64"]
+ complex: L["complex128"]
+ object: L["object_"]
+ bytes: L["bytes_"]
+ a: L["bytes_"]
+ int: L["int_"]
+ str: L["str_"]
+ unicode: L["str_"]
+
+_extra_aliases: Final[_ExtraAliasesType]
+
+@type_check_only
+class _SCTypes(TypedDict):
+ int: Collection[type[np.signedinteger[Any]]]
+ uint: Collection[type[np.unsignedinteger[Any]]]
+ float: Collection[type[np.floating[Any]]]
+ complex: Collection[type[np.complexfloating[Any, Any]]]
+ others: Collection[type[np.flexible | np.bool | np.object_]]
+
+sctypes: Final[_SCTypes]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_ufunc_config.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_ufunc_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..4563f66cb52f521b762bf6a2134c319328c5ef92
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_ufunc_config.py
@@ -0,0 +1,483 @@
+"""
+Functions for changing global ufunc configuration
+
+This provides helpers which wrap `_get_extobj_dict` and `_make_extobj`, and
+`_extobj_contextvar` from umath.
+"""
+import contextlib
+import contextvars
+import functools
+
+from .._utils import set_module
+from .umath import _make_extobj, _get_extobj_dict, _extobj_contextvar
+
+__all__ = [
+ "seterr", "geterr", "setbufsize", "getbufsize", "seterrcall", "geterrcall",
+ "errstate"
+]
+
+
+@set_module('numpy')
+def seterr(all=None, divide=None, over=None, under=None, invalid=None):
+ """
+ Set how floating-point errors are handled.
+
+ Note that operations on integer scalar types (such as `int16`) are
+ handled like floating point, and are affected by these settings.
+
+ Parameters
+ ----------
+ all : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
+ Set treatment for all types of floating-point errors at once:
+
+ - ignore: Take no action when the exception occurs.
+ - warn: Print a :exc:`RuntimeWarning` (via the Python `warnings`
+ module).
+ - raise: Raise a :exc:`FloatingPointError`.
+ - call: Call a function specified using the `seterrcall` function.
+ - print: Print a warning directly to ``stdout``.
+ - log: Record error in a Log object specified by `seterrcall`.
+
+ The default is not to change the current behavior.
+ divide : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
+ Treatment for division by zero.
+ over : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
+ Treatment for floating-point overflow.
+ under : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
+ Treatment for floating-point underflow.
+ invalid : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
+ Treatment for invalid floating-point operation.
+
+ Returns
+ -------
+ old_settings : dict
+ Dictionary containing the old settings.
+
+ See also
+ --------
+ seterrcall : Set a callback function for the 'call' mode.
+ geterr, geterrcall, errstate
+
+ Notes
+ -----
+ The floating-point exceptions are defined in the IEEE 754 standard [1]_:
+
+ - Division by zero: infinite result obtained from finite numbers.
+ - Overflow: result too large to be expressed.
+ - Underflow: result so close to zero that some precision
+ was lost.
+ - Invalid operation: result is not an expressible number, typically
+ indicates that a NaN was produced.
+
+ .. [1] https://en.wikipedia.org/wiki/IEEE_754
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> orig_settings = np.seterr(all='ignore') # seterr to known value
+ >>> np.int16(32000) * np.int16(3)
+ np.int16(30464)
+ >>> np.seterr(over='raise')
+ {'divide': 'ignore', 'over': 'ignore', 'under': 'ignore', 'invalid': 'ignore'}
+ >>> old_settings = np.seterr(all='warn', over='raise')
+ >>> np.int16(32000) * np.int16(3)
+ Traceback (most recent call last):
+ File "", line 1, in
+ FloatingPointError: overflow encountered in scalar multiply
+
+ >>> old_settings = np.seterr(all='print')
+ >>> np.geterr()
+ {'divide': 'print', 'over': 'print', 'under': 'print', 'invalid': 'print'}
+ >>> np.int16(32000) * np.int16(3)
+ np.int16(30464)
+ >>> np.seterr(**orig_settings) # restore original
+ {'divide': 'print', 'over': 'print', 'under': 'print', 'invalid': 'print'}
+
+ """
+
+ old = _get_extobj_dict()
+ # The errstate doesn't include call and bufsize, so pop them:
+ old.pop("call", None)
+ old.pop("bufsize", None)
+
+ extobj = _make_extobj(
+ all=all, divide=divide, over=over, under=under, invalid=invalid)
+ _extobj_contextvar.set(extobj)
+ return old
+
+
+@set_module('numpy')
+def geterr():
+ """
+ Get the current way of handling floating-point errors.
+
+ Returns
+ -------
+ res : dict
+ A dictionary with keys "divide", "over", "under", and "invalid",
+ whose values are from the strings "ignore", "print", "log", "warn",
+ "raise", and "call". The keys represent possible floating-point
+ exceptions, and the values define how these exceptions are handled.
+
+ See Also
+ --------
+ geterrcall, seterr, seterrcall
+
+ Notes
+ -----
+ For complete documentation of the types of floating-point exceptions and
+ treatment options, see `seterr`.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.geterr()
+ {'divide': 'warn', 'over': 'warn', 'under': 'ignore', 'invalid': 'warn'}
+ >>> np.arange(3.) / np.arange(3.) # doctest: +SKIP
+ array([nan, 1., 1.])
+ RuntimeWarning: invalid value encountered in divide
+
+ >>> oldsettings = np.seterr(all='warn', invalid='raise')
+ >>> np.geterr()
+ {'divide': 'warn', 'over': 'warn', 'under': 'warn', 'invalid': 'raise'}
+ >>> np.arange(3.) / np.arange(3.)
+ Traceback (most recent call last):
+ ...
+ FloatingPointError: invalid value encountered in divide
+ >>> oldsettings = np.seterr(**oldsettings) # restore original
+
+ """
+ res = _get_extobj_dict()
+ # The "geterr" doesn't include call and bufsize,:
+ res.pop("call", None)
+ res.pop("bufsize", None)
+ return res
+
+
+@set_module('numpy')
+def setbufsize(size):
+ """
+ Set the size of the buffer used in ufuncs.
+
+ .. versionchanged:: 2.0
+ The scope of setting the buffer is tied to the `numpy.errstate`
+ context. Exiting a ``with errstate():`` will also restore the bufsize.
+
+ Parameters
+ ----------
+ size : int
+ Size of buffer.
+
+ Returns
+ -------
+ bufsize : int
+ Previous size of ufunc buffer in bytes.
+
+ Examples
+ --------
+ When exiting a `numpy.errstate` context manager the bufsize is restored:
+
+ >>> import numpy as np
+ >>> with np.errstate():
+ ... np.setbufsize(4096)
+ ... print(np.getbufsize())
+ ...
+ 8192
+ 4096
+ >>> np.getbufsize()
+ 8192
+
+ """
+ old = _get_extobj_dict()["bufsize"]
+ extobj = _make_extobj(bufsize=size)
+ _extobj_contextvar.set(extobj)
+ return old
+
+
+@set_module('numpy')
+def getbufsize():
+ """
+ Return the size of the buffer used in ufuncs.
+
+ Returns
+ -------
+ getbufsize : int
+ Size of ufunc buffer in bytes.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.getbufsize()
+ 8192
+
+ """
+ return _get_extobj_dict()["bufsize"]
+
+
+@set_module('numpy')
+def seterrcall(func):
+ """
+ Set the floating-point error callback function or log object.
+
+ There are two ways to capture floating-point error messages. The first
+ is to set the error-handler to 'call', using `seterr`. Then, set
+ the function to call using this function.
+
+ The second is to set the error-handler to 'log', using `seterr`.
+ Floating-point errors then trigger a call to the 'write' method of
+ the provided object.
+
+ Parameters
+ ----------
+ func : callable f(err, flag) or object with write method
+ Function to call upon floating-point errors ('call'-mode) or
+ object whose 'write' method is used to log such message ('log'-mode).
+
+ The call function takes two arguments. The first is a string describing
+ the type of error (such as "divide by zero", "overflow", "underflow",
+ or "invalid value"), and the second is the status flag. The flag is a
+ byte, whose four least-significant bits indicate the type of error, one
+ of "divide", "over", "under", "invalid"::
+
+ [0 0 0 0 divide over under invalid]
+
+ In other words, ``flags = divide + 2*over + 4*under + 8*invalid``.
+
+ If an object is provided, its write method should take one argument,
+ a string.
+
+ Returns
+ -------
+ h : callable, log instance or None
+ The old error handler.
+
+ See Also
+ --------
+ seterr, geterr, geterrcall
+
+ Examples
+ --------
+ Callback upon error:
+
+ >>> def err_handler(type, flag):
+ ... print("Floating point error (%s), with flag %s" % (type, flag))
+ ...
+
+ >>> import numpy as np
+
+ >>> orig_handler = np.seterrcall(err_handler)
+ >>> orig_err = np.seterr(all='call')
+
+ >>> np.array([1, 2, 3]) / 0.0
+ Floating point error (divide by zero), with flag 1
+ array([inf, inf, inf])
+
+ >>> np.seterrcall(orig_handler)
+
+ >>> np.seterr(**orig_err)
+ {'divide': 'call', 'over': 'call', 'under': 'call', 'invalid': 'call'}
+
+ Log error message:
+
+ >>> class Log:
+ ... def write(self, msg):
+ ... print("LOG: %s" % msg)
+ ...
+
+ >>> log = Log()
+ >>> saved_handler = np.seterrcall(log)
+ >>> save_err = np.seterr(all='log')
+
+ >>> np.array([1, 2, 3]) / 0.0
+ LOG: Warning: divide by zero encountered in divide
+ array([inf, inf, inf])
+
+ >>> np.seterrcall(orig_handler)
+
+ >>> np.seterr(**orig_err)
+ {'divide': 'log', 'over': 'log', 'under': 'log', 'invalid': 'log'}
+
+ """
+ old = _get_extobj_dict()["call"]
+ extobj = _make_extobj(call=func)
+ _extobj_contextvar.set(extobj)
+ return old
+
+
+@set_module('numpy')
+def geterrcall():
+ """
+ Return the current callback function used on floating-point errors.
+
+ When the error handling for a floating-point error (one of "divide",
+ "over", "under", or "invalid") is set to 'call' or 'log', the function
+ that is called or the log instance that is written to is returned by
+ `geterrcall`. This function or log instance has been set with
+ `seterrcall`.
+
+ Returns
+ -------
+ errobj : callable, log instance or None
+ The current error handler. If no handler was set through `seterrcall`,
+ ``None`` is returned.
+
+ See Also
+ --------
+ seterrcall, seterr, geterr
+
+ Notes
+ -----
+ For complete documentation of the types of floating-point exceptions and
+ treatment options, see `seterr`.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.geterrcall() # we did not yet set a handler, returns None
+
+ >>> orig_settings = np.seterr(all='call')
+ >>> def err_handler(type, flag):
+ ... print("Floating point error (%s), with flag %s" % (type, flag))
+ >>> old_handler = np.seterrcall(err_handler)
+ >>> np.array([1, 2, 3]) / 0.0
+ Floating point error (divide by zero), with flag 1
+ array([inf, inf, inf])
+
+ >>> cur_handler = np.geterrcall()
+ >>> cur_handler is err_handler
+ True
+ >>> old_settings = np.seterr(**orig_settings) # restore original
+ >>> old_handler = np.seterrcall(None) # restore original
+
+ """
+ return _get_extobj_dict()["call"]
+
+
+class _unspecified:
+ pass
+
+
+_Unspecified = _unspecified()
+
+
+@set_module('numpy')
+class errstate:
+ """
+ errstate(**kwargs)
+
+ Context manager for floating-point error handling.
+
+ Using an instance of `errstate` as a context manager allows statements in
+ that context to execute with a known error handling behavior. Upon entering
+ the context the error handling is set with `seterr` and `seterrcall`, and
+ upon exiting it is reset to what it was before.
+
+ .. versionchanged:: 1.17.0
+ `errstate` is also usable as a function decorator, saving
+ a level of indentation if an entire function is wrapped.
+
+ .. versionchanged:: 2.0
+ `errstate` is now fully thread and asyncio safe, but may not be
+ entered more than once.
+ It is not safe to decorate async functions using ``errstate``.
+
+ Parameters
+ ----------
+ kwargs : {divide, over, under, invalid}
+ Keyword arguments. The valid keywords are the possible floating-point
+ exceptions. Each keyword should have a string value that defines the
+ treatment for the particular error. Possible values are
+ {'ignore', 'warn', 'raise', 'call', 'print', 'log'}.
+
+ See Also
+ --------
+ seterr, geterr, seterrcall, geterrcall
+
+ Notes
+ -----
+ For complete documentation of the types of floating-point exceptions and
+ treatment options, see `seterr`.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> olderr = np.seterr(all='ignore') # Set error handling to known state.
+
+ >>> np.arange(3) / 0.
+ array([nan, inf, inf])
+ >>> with np.errstate(divide='ignore'):
+ ... np.arange(3) / 0.
+ array([nan, inf, inf])
+
+ >>> np.sqrt(-1)
+ np.float64(nan)
+ >>> with np.errstate(invalid='raise'):
+ ... np.sqrt(-1)
+ Traceback (most recent call last):
+ File "", line 2, in
+ FloatingPointError: invalid value encountered in sqrt
+
+ Outside the context the error handling behavior has not changed:
+
+ >>> np.geterr()
+ {'divide': 'ignore', 'over': 'ignore', 'under': 'ignore', 'invalid': 'ignore'}
+ >>> olderr = np.seterr(**olderr) # restore original state
+
+ """
+ __slots__ = (
+ "_call", "_all", "_divide", "_over", "_under", "_invalid", "_token")
+
+ def __init__(self, *, call=_Unspecified,
+ all=None, divide=None, over=None, under=None, invalid=None):
+ self._token = None
+ self._call = call
+ self._all = all
+ self._divide = divide
+ self._over = over
+ self._under = under
+ self._invalid = invalid
+
+ def __enter__(self):
+ # Note that __call__ duplicates much of this logic
+ if self._token is not None:
+ raise TypeError("Cannot enter `np.errstate` twice.")
+ if self._call is _Unspecified:
+ extobj = _make_extobj(
+ all=self._all, divide=self._divide, over=self._over,
+ under=self._under, invalid=self._invalid)
+ else:
+ extobj = _make_extobj(
+ call=self._call,
+ all=self._all, divide=self._divide, over=self._over,
+ under=self._under, invalid=self._invalid)
+
+ self._token = _extobj_contextvar.set(extobj)
+
+ def __exit__(self, *exc_info):
+ _extobj_contextvar.reset(self._token)
+
+ def __call__(self, func):
+ # We need to customize `__call__` compared to `ContextDecorator`
+ # because we must store the token per-thread so cannot store it on
+ # the instance (we could create a new instance for this).
+ # This duplicates the code from `__enter__`.
+ @functools.wraps(func)
+ def inner(*args, **kwargs):
+ if self._call is _Unspecified:
+ extobj = _make_extobj(
+ all=self._all, divide=self._divide, over=self._over,
+ under=self._under, invalid=self._invalid)
+ else:
+ extobj = _make_extobj(
+ call=self._call,
+ all=self._all, divide=self._divide, over=self._over,
+ under=self._under, invalid=self._invalid)
+
+ _token = _extobj_contextvar.set(extobj)
+ try:
+ # Call the original, decorated, function:
+ return func(*args, **kwargs)
+ finally:
+ _extobj_contextvar.reset(_token)
+
+ return inner
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_ufunc_config.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_ufunc_config.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..78c9660323d1257e913bc62f9ade1ad21cef87dd
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_ufunc_config.pyi
@@ -0,0 +1,39 @@
+from _typeshed import SupportsWrite
+from collections.abc import Callable
+from typing import Any, Literal, TypeAlias, TypedDict, type_check_only
+
+from numpy import errstate as errstate
+
+_ErrKind: TypeAlias = Literal["ignore", "warn", "raise", "call", "print", "log"]
+_ErrFunc: TypeAlias = Callable[[str, int], Any]
+_ErrCall: TypeAlias = _ErrFunc | SupportsWrite[str]
+
+@type_check_only
+class _ErrDict(TypedDict):
+ divide: _ErrKind
+ over: _ErrKind
+ under: _ErrKind
+ invalid: _ErrKind
+
+@type_check_only
+class _ErrDictOptional(TypedDict, total=False):
+ all: None | _ErrKind
+ divide: None | _ErrKind
+ over: None | _ErrKind
+ under: None | _ErrKind
+ invalid: None | _ErrKind
+
+def seterr(
+ all: None | _ErrKind = ...,
+ divide: None | _ErrKind = ...,
+ over: None | _ErrKind = ...,
+ under: None | _ErrKind = ...,
+ invalid: None | _ErrKind = ...,
+) -> _ErrDict: ...
+def geterr() -> _ErrDict: ...
+def setbufsize(size: int) -> int: ...
+def getbufsize() -> int: ...
+def seterrcall(func: _ErrCall | None) -> _ErrCall | None: ...
+def geterrcall() -> _ErrCall | None: ...
+
+# See `numpy/__init__.pyi` for the `errstate` class and `no_nep5_warnings`
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_umath_tests.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_umath_tests.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..70a9651056856e4279991ed37d12cca2d74234af
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/_umath_tests.cpython-310-x86_64-linux-gnu.so differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/arrayprint.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/arrayprint.py
new file mode 100644
index 0000000000000000000000000000000000000000..d95093a6a4e11983bac70eba7f572ddc955a6aed
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/arrayprint.py
@@ -0,0 +1,1756 @@
+"""Array printing function
+
+$Id: arrayprint.py,v 1.9 2005/09/13 13:58:44 teoliphant Exp $
+
+"""
+__all__ = ["array2string", "array_str", "array_repr",
+ "set_printoptions", "get_printoptions", "printoptions",
+ "format_float_positional", "format_float_scientific"]
+__docformat__ = 'restructuredtext'
+
+#
+# Written by Konrad Hinsen
+# last revision: 1996-3-13
+# modified by Jim Hugunin 1997-3-3 for repr's and str's (and other details)
+# and by Perry Greenfield 2000-4-1 for numarray
+# and by Travis Oliphant 2005-8-22 for numpy
+
+
+# Note: Both scalartypes.c.src and arrayprint.py implement strs for numpy
+# scalars but for different purposes. scalartypes.c.src has str/reprs for when
+# the scalar is printed on its own, while arrayprint.py has strs for when
+# scalars are printed inside an ndarray. Only the latter strs are currently
+# user-customizable.
+
+import functools
+import numbers
+import sys
+try:
+ from _thread import get_ident
+except ImportError:
+ from _dummy_thread import get_ident
+
+import numpy as np
+from . import numerictypes as _nt
+from .umath import absolute, isinf, isfinite, isnat
+from . import multiarray
+from .multiarray import (array, dragon4_positional, dragon4_scientific,
+ datetime_as_string, datetime_data, ndarray)
+from .fromnumeric import any
+from .numeric import concatenate, asarray, errstate
+from .numerictypes import (longlong, intc, int_, float64, complex128,
+ flexible)
+from .overrides import array_function_dispatch, set_module
+from .printoptions import format_options
+import operator
+import warnings
+import contextlib
+
+
+def _make_options_dict(precision=None, threshold=None, edgeitems=None,
+ linewidth=None, suppress=None, nanstr=None, infstr=None,
+ sign=None, formatter=None, floatmode=None, legacy=None,
+ override_repr=None):
+ """
+ Make a dictionary out of the non-None arguments, plus conversion of
+ *legacy* and sanity checks.
+ """
+
+ options = {k: v for k, v in list(locals().items()) if v is not None}
+
+ if suppress is not None:
+ options['suppress'] = bool(suppress)
+
+ modes = ['fixed', 'unique', 'maxprec', 'maxprec_equal']
+ if floatmode not in modes + [None]:
+ raise ValueError("floatmode option must be one of " +
+ ", ".join('"{}"'.format(m) for m in modes))
+
+ if sign not in [None, '-', '+', ' ']:
+ raise ValueError("sign option must be one of ' ', '+', or '-'")
+
+ if legacy is False:
+ options['legacy'] = sys.maxsize
+ elif legacy == False: # noqa: E712
+ warnings.warn(
+ f"Passing `legacy={legacy!r}` is deprecated.",
+ FutureWarning, stacklevel=3
+ )
+ options['legacy'] = sys.maxsize
+ elif legacy == '1.13':
+ options['legacy'] = 113
+ elif legacy == '1.21':
+ options['legacy'] = 121
+ elif legacy == '1.25':
+ options['legacy'] = 125
+ elif legacy == '2.1':
+ options['legacy'] = 201
+ elif legacy is None:
+ pass # OK, do nothing.
+ else:
+ warnings.warn(
+ "legacy printing option can currently only be '1.13', '1.21', "
+ "'1.25', '2.1, or `False`", stacklevel=3)
+
+ if threshold is not None:
+ # forbid the bad threshold arg suggested by stack overflow, gh-12351
+ if not isinstance(threshold, numbers.Number):
+ raise TypeError("threshold must be numeric")
+ if np.isnan(threshold):
+ raise ValueError("threshold must be non-NAN, try "
+ "sys.maxsize for untruncated representation")
+
+ if precision is not None:
+ # forbid the bad precision arg as suggested by issue #18254
+ try:
+ options['precision'] = operator.index(precision)
+ except TypeError as e:
+ raise TypeError('precision must be an integer') from e
+
+ return options
+
+
+@set_module('numpy')
+def set_printoptions(precision=None, threshold=None, edgeitems=None,
+ linewidth=None, suppress=None, nanstr=None,
+ infstr=None, formatter=None, sign=None, floatmode=None,
+ *, legacy=None, override_repr=None):
+ """
+ Set printing options.
+
+ These options determine the way floating point numbers, arrays and
+ other NumPy objects are displayed.
+
+ Parameters
+ ----------
+ precision : int or None, optional
+ Number of digits of precision for floating point output (default 8).
+ May be None if `floatmode` is not `fixed`, to print as many digits as
+ necessary to uniquely specify the value.
+ threshold : int, optional
+ Total number of array elements which trigger summarization
+ rather than full repr (default 1000).
+ To always use the full repr without summarization, pass `sys.maxsize`.
+ edgeitems : int, optional
+ Number of array items in summary at beginning and end of
+ each dimension (default 3).
+ linewidth : int, optional
+ The number of characters per line for the purpose of inserting
+ line breaks (default 75).
+ suppress : bool, optional
+ If True, always print floating point numbers using fixed point
+ notation, in which case numbers equal to zero in the current precision
+ will print as zero. If False, then scientific notation is used when
+ absolute value of the smallest number is < 1e-4 or the ratio of the
+ maximum absolute value to the minimum is > 1e3. The default is False.
+ nanstr : str, optional
+ String representation of floating point not-a-number (default nan).
+ infstr : str, optional
+ String representation of floating point infinity (default inf).
+ sign : string, either '-', '+', or ' ', optional
+ Controls printing of the sign of floating-point types. If '+', always
+ print the sign of positive values. If ' ', always prints a space
+ (whitespace character) in the sign position of positive values. If
+ '-', omit the sign character of positive values. (default '-')
+
+ .. versionchanged:: 2.0
+ The sign parameter can now be an integer type, previously
+ types were floating-point types.
+
+ formatter : dict of callables, optional
+ If not None, the keys should indicate the type(s) that the respective
+ formatting function applies to. Callables should return a string.
+ Types that are not specified (by their corresponding keys) are handled
+ by the default formatters. Individual types for which a formatter
+ can be set are:
+
+ - 'bool'
+ - 'int'
+ - 'timedelta' : a `numpy.timedelta64`
+ - 'datetime' : a `numpy.datetime64`
+ - 'float'
+ - 'longfloat' : 128-bit floats
+ - 'complexfloat'
+ - 'longcomplexfloat' : composed of two 128-bit floats
+ - 'numpystr' : types `numpy.bytes_` and `numpy.str_`
+ - 'object' : `np.object_` arrays
+
+ Other keys that can be used to set a group of types at once are:
+
+ - 'all' : sets all types
+ - 'int_kind' : sets 'int'
+ - 'float_kind' : sets 'float' and 'longfloat'
+ - 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat'
+ - 'str_kind' : sets 'numpystr'
+ floatmode : str, optional
+ Controls the interpretation of the `precision` option for
+ floating-point types. Can take the following values
+ (default maxprec_equal):
+
+ * 'fixed': Always print exactly `precision` fractional digits,
+ even if this would print more or fewer digits than
+ necessary to specify the value uniquely.
+ * 'unique': Print the minimum number of fractional digits necessary
+ to represent each value uniquely. Different elements may
+ have a different number of digits. The value of the
+ `precision` option is ignored.
+ * 'maxprec': Print at most `precision` fractional digits, but if
+ an element can be uniquely represented with fewer digits
+ only print it with that many.
+ * 'maxprec_equal': Print at most `precision` fractional digits,
+ but if every element in the array can be uniquely
+ represented with an equal number of fewer digits, use that
+ many digits for all elements.
+ legacy : string or `False`, optional
+ If set to the string ``'1.13'`` enables 1.13 legacy printing mode. This
+ approximates numpy 1.13 print output by including a space in the sign
+ position of floats and different behavior for 0d arrays. This also
+ enables 1.21 legacy printing mode (described below).
+
+ If set to the string ``'1.21'`` enables 1.21 legacy printing mode. This
+ approximates numpy 1.21 print output of complex structured dtypes
+ by not inserting spaces after commas that separate fields and after
+ colons.
+
+ If set to ``'1.25'`` approximates printing of 1.25 which mainly means
+ that numeric scalars are printed without their type information, e.g.
+ as ``3.0`` rather than ``np.float64(3.0)``.
+
+ If set to ``'2.1'``, shape information is not given when arrays are
+ summarized (i.e., multiple elements replaced with ``...``).
+
+ If set to `False`, disables legacy mode.
+
+ Unrecognized strings will be ignored with a warning for forward
+ compatibility.
+
+ .. versionchanged:: 1.22.0
+ .. versionchanged:: 2.2
+
+ override_repr: callable, optional
+ If set a passed function will be used for generating arrays' repr.
+ Other options will be ignored.
+
+ See Also
+ --------
+ get_printoptions, printoptions, array2string
+
+ Notes
+ -----
+ `formatter` is always reset with a call to `set_printoptions`.
+
+ Use `printoptions` as a context manager to set the values temporarily.
+
+ Examples
+ --------
+ Floating point precision can be set:
+
+ >>> import numpy as np
+ >>> np.set_printoptions(precision=4)
+ >>> np.array([1.123456789])
+ [1.1235]
+
+ Long arrays can be summarised:
+
+ >>> np.set_printoptions(threshold=5)
+ >>> np.arange(10)
+ array([0, 1, 2, ..., 7, 8, 9], shape=(10,))
+
+ Small results can be suppressed:
+
+ >>> eps = np.finfo(float).eps
+ >>> x = np.arange(4.)
+ >>> x**2 - (x + eps)**2
+ array([-4.9304e-32, -4.4409e-16, 0.0000e+00, 0.0000e+00])
+ >>> np.set_printoptions(suppress=True)
+ >>> x**2 - (x + eps)**2
+ array([-0., -0., 0., 0.])
+
+ A custom formatter can be used to display array elements as desired:
+
+ >>> np.set_printoptions(formatter={'all':lambda x: 'int: '+str(-x)})
+ >>> x = np.arange(3)
+ >>> x
+ array([int: 0, int: -1, int: -2])
+ >>> np.set_printoptions() # formatter gets reset
+ >>> x
+ array([0, 1, 2])
+
+ To put back the default options, you can use:
+
+ >>> np.set_printoptions(edgeitems=3, infstr='inf',
+ ... linewidth=75, nanstr='nan', precision=8,
+ ... suppress=False, threshold=1000, formatter=None)
+
+ Also to temporarily override options, use `printoptions`
+ as a context manager:
+
+ >>> with np.printoptions(precision=2, suppress=True, threshold=5):
+ ... np.linspace(0, 10, 10)
+ array([ 0. , 1.11, 2.22, ..., 7.78, 8.89, 10. ], shape=(10,))
+
+ """
+ _set_printoptions(precision, threshold, edgeitems, linewidth, suppress,
+ nanstr, infstr, formatter, sign, floatmode,
+ legacy=legacy, override_repr=override_repr)
+
+
+def _set_printoptions(precision=None, threshold=None, edgeitems=None,
+ linewidth=None, suppress=None, nanstr=None,
+ infstr=None, formatter=None, sign=None, floatmode=None,
+ *, legacy=None, override_repr=None):
+ new_opt = _make_options_dict(precision, threshold, edgeitems, linewidth,
+ suppress, nanstr, infstr, sign, formatter,
+ floatmode, legacy)
+ # formatter and override_repr are always reset
+ new_opt['formatter'] = formatter
+ new_opt['override_repr'] = override_repr
+
+ updated_opt = format_options.get() | new_opt
+ updated_opt.update(new_opt)
+
+ if updated_opt['legacy'] == 113:
+ updated_opt['sign'] = '-'
+
+ return format_options.set(updated_opt)
+
+
+@set_module('numpy')
+def get_printoptions():
+ """
+ Return the current print options.
+
+ Returns
+ -------
+ print_opts : dict
+ Dictionary of current print options with keys
+
+ - precision : int
+ - threshold : int
+ - edgeitems : int
+ - linewidth : int
+ - suppress : bool
+ - nanstr : str
+ - infstr : str
+ - sign : str
+ - formatter : dict of callables
+ - floatmode : str
+ - legacy : str or False
+
+ For a full description of these options, see `set_printoptions`.
+
+ See Also
+ --------
+ set_printoptions, printoptions
+
+ Examples
+ --------
+ >>> import numpy as np
+
+ >>> np.get_printoptions()
+ {'edgeitems': 3, 'threshold': 1000, ..., 'override_repr': None}
+
+ >>> np.get_printoptions()['linewidth']
+ 75
+ >>> np.set_printoptions(linewidth=100)
+ >>> np.get_printoptions()['linewidth']
+ 100
+
+ """
+ opts = format_options.get().copy()
+ opts['legacy'] = {
+ 113: '1.13', 121: '1.21', 125: '1.25', sys.maxsize: False,
+ }[opts['legacy']]
+ return opts
+
+
+def _get_legacy_print_mode():
+ """Return the legacy print mode as an int."""
+ return format_options.get()['legacy']
+
+
+@set_module('numpy')
+@contextlib.contextmanager
+def printoptions(*args, **kwargs):
+ """Context manager for setting print options.
+
+ Set print options for the scope of the `with` block, and restore the old
+ options at the end. See `set_printoptions` for the full description of
+ available options.
+
+ Examples
+ --------
+ >>> import numpy as np
+
+ >>> from numpy.testing import assert_equal
+ >>> with np.printoptions(precision=2):
+ ... np.array([2.0]) / 3
+ array([0.67])
+
+ The `as`-clause of the `with`-statement gives the current print options:
+
+ >>> with np.printoptions(precision=2) as opts:
+ ... assert_equal(opts, np.get_printoptions())
+
+ See Also
+ --------
+ set_printoptions, get_printoptions
+
+ """
+ token = _set_printoptions(*args, **kwargs)
+
+ try:
+ yield get_printoptions()
+ finally:
+ format_options.reset(token)
+
+
+def _leading_trailing(a, edgeitems, index=()):
+ """
+ Keep only the N-D corners (leading and trailing edges) of an array.
+
+ Should be passed a base-class ndarray, since it makes no guarantees about
+ preserving subclasses.
+ """
+ axis = len(index)
+ if axis == a.ndim:
+ return a[index]
+
+ if a.shape[axis] > 2*edgeitems:
+ return concatenate((
+ _leading_trailing(a, edgeitems, index + np.index_exp[:edgeitems]),
+ _leading_trailing(a, edgeitems, index + np.index_exp[-edgeitems:])
+ ), axis=axis)
+ else:
+ return _leading_trailing(a, edgeitems, index + np.index_exp[:])
+
+
+def _object_format(o):
+ """ Object arrays containing lists should be printed unambiguously """
+ if type(o) is list:
+ fmt = 'list({!r})'
+ else:
+ fmt = '{!r}'
+ return fmt.format(o)
+
+def repr_format(x):
+ if isinstance(x, (np.str_, np.bytes_)):
+ return repr(x.item())
+ return repr(x)
+
+def str_format(x):
+ if isinstance(x, (np.str_, np.bytes_)):
+ return str(x.item())
+ return str(x)
+
+def _get_formatdict(data, *, precision, floatmode, suppress, sign, legacy,
+ formatter, **kwargs):
+ # note: extra arguments in kwargs are ignored
+
+ # wrapped in lambdas to avoid taking a code path
+ # with the wrong type of data
+ formatdict = {
+ 'bool': lambda: BoolFormat(data),
+ 'int': lambda: IntegerFormat(data, sign),
+ 'float': lambda: FloatingFormat(
+ data, precision, floatmode, suppress, sign, legacy=legacy),
+ 'longfloat': lambda: FloatingFormat(
+ data, precision, floatmode, suppress, sign, legacy=legacy),
+ 'complexfloat': lambda: ComplexFloatingFormat(
+ data, precision, floatmode, suppress, sign, legacy=legacy),
+ 'longcomplexfloat': lambda: ComplexFloatingFormat(
+ data, precision, floatmode, suppress, sign, legacy=legacy),
+ 'datetime': lambda: DatetimeFormat(data, legacy=legacy),
+ 'timedelta': lambda: TimedeltaFormat(data),
+ 'object': lambda: _object_format,
+ 'void': lambda: str_format,
+ 'numpystr': lambda: repr_format}
+
+ # we need to wrap values in `formatter` in a lambda, so that the interface
+ # is the same as the above values.
+ def indirect(x):
+ return lambda: x
+
+ if formatter is not None:
+ fkeys = [k for k in formatter.keys() if formatter[k] is not None]
+ if 'all' in fkeys:
+ for key in formatdict.keys():
+ formatdict[key] = indirect(formatter['all'])
+ if 'int_kind' in fkeys:
+ for key in ['int']:
+ formatdict[key] = indirect(formatter['int_kind'])
+ if 'float_kind' in fkeys:
+ for key in ['float', 'longfloat']:
+ formatdict[key] = indirect(formatter['float_kind'])
+ if 'complex_kind' in fkeys:
+ for key in ['complexfloat', 'longcomplexfloat']:
+ formatdict[key] = indirect(formatter['complex_kind'])
+ if 'str_kind' in fkeys:
+ formatdict['numpystr'] = indirect(formatter['str_kind'])
+ for key in formatdict.keys():
+ if key in fkeys:
+ formatdict[key] = indirect(formatter[key])
+
+ return formatdict
+
+def _get_format_function(data, **options):
+ """
+ find the right formatting function for the dtype_
+ """
+ dtype_ = data.dtype
+ dtypeobj = dtype_.type
+ formatdict = _get_formatdict(data, **options)
+ if dtypeobj is None:
+ return formatdict["numpystr"]()
+ elif issubclass(dtypeobj, _nt.bool):
+ return formatdict['bool']()
+ elif issubclass(dtypeobj, _nt.integer):
+ if issubclass(dtypeobj, _nt.timedelta64):
+ return formatdict['timedelta']()
+ else:
+ return formatdict['int']()
+ elif issubclass(dtypeobj, _nt.floating):
+ if issubclass(dtypeobj, _nt.longdouble):
+ return formatdict['longfloat']()
+ else:
+ return formatdict['float']()
+ elif issubclass(dtypeobj, _nt.complexfloating):
+ if issubclass(dtypeobj, _nt.clongdouble):
+ return formatdict['longcomplexfloat']()
+ else:
+ return formatdict['complexfloat']()
+ elif issubclass(dtypeobj, (_nt.str_, _nt.bytes_)):
+ return formatdict['numpystr']()
+ elif issubclass(dtypeobj, _nt.datetime64):
+ return formatdict['datetime']()
+ elif issubclass(dtypeobj, _nt.object_):
+ return formatdict['object']()
+ elif issubclass(dtypeobj, _nt.void):
+ if dtype_.names is not None:
+ return StructuredVoidFormat.from_data(data, **options)
+ else:
+ return formatdict['void']()
+ else:
+ return formatdict['numpystr']()
+
+
+def _recursive_guard(fillvalue='...'):
+ """
+ Like the python 3.2 reprlib.recursive_repr, but forwards *args and **kwargs
+
+ Decorates a function such that if it calls itself with the same first
+ argument, it returns `fillvalue` instead of recursing.
+
+ Largely copied from reprlib.recursive_repr
+ """
+
+ def decorating_function(f):
+ repr_running = set()
+
+ @functools.wraps(f)
+ def wrapper(self, *args, **kwargs):
+ key = id(self), get_ident()
+ if key in repr_running:
+ return fillvalue
+ repr_running.add(key)
+ try:
+ return f(self, *args, **kwargs)
+ finally:
+ repr_running.discard(key)
+
+ return wrapper
+
+ return decorating_function
+
+
+# gracefully handle recursive calls, when object arrays contain themselves
+@_recursive_guard()
+def _array2string(a, options, separator=' ', prefix=""):
+ # The formatter __init__s in _get_format_function cannot deal with
+ # subclasses yet, and we also need to avoid recursion issues in
+ # _formatArray with subclasses which return 0d arrays in place of scalars
+ data = asarray(a)
+ if a.shape == ():
+ a = data
+
+ if a.size > options['threshold']:
+ summary_insert = "..."
+ data = _leading_trailing(data, options['edgeitems'])
+ else:
+ summary_insert = ""
+
+ # find the right formatting function for the array
+ format_function = _get_format_function(data, **options)
+
+ # skip over "["
+ next_line_prefix = " "
+ # skip over array(
+ next_line_prefix += " "*len(prefix)
+
+ lst = _formatArray(a, format_function, options['linewidth'],
+ next_line_prefix, separator, options['edgeitems'],
+ summary_insert, options['legacy'])
+ return lst
+
+
+def _array2string_dispatcher(
+ a, max_line_width=None, precision=None,
+ suppress_small=None, separator=None, prefix=None,
+ style=None, formatter=None, threshold=None,
+ edgeitems=None, sign=None, floatmode=None, suffix=None,
+ *, legacy=None):
+ return (a,)
+
+
+@array_function_dispatch(_array2string_dispatcher, module='numpy')
+def array2string(a, max_line_width=None, precision=None,
+ suppress_small=None, separator=' ', prefix="",
+ style=np._NoValue, formatter=None, threshold=None,
+ edgeitems=None, sign=None, floatmode=None, suffix="",
+ *, legacy=None):
+ """
+ Return a string representation of an array.
+
+ Parameters
+ ----------
+ a : ndarray
+ Input array.
+ max_line_width : int, optional
+ Inserts newlines if text is longer than `max_line_width`.
+ Defaults to ``numpy.get_printoptions()['linewidth']``.
+ precision : int or None, optional
+ Floating point precision.
+ Defaults to ``numpy.get_printoptions()['precision']``.
+ suppress_small : bool, optional
+ Represent numbers "very close" to zero as zero; default is False.
+ Very close is defined by precision: if the precision is 8, e.g.,
+ numbers smaller (in absolute value) than 5e-9 are represented as
+ zero.
+ Defaults to ``numpy.get_printoptions()['suppress']``.
+ separator : str, optional
+ Inserted between elements.
+ prefix : str, optional
+ suffix : str, optional
+ The length of the prefix and suffix strings are used to respectively
+ align and wrap the output. An array is typically printed as::
+
+ prefix + array2string(a) + suffix
+
+ The output is left-padded by the length of the prefix string, and
+ wrapping is forced at the column ``max_line_width - len(suffix)``.
+ It should be noted that the content of prefix and suffix strings are
+ not included in the output.
+ style : _NoValue, optional
+ Has no effect, do not use.
+
+ .. deprecated:: 1.14.0
+ formatter : dict of callables, optional
+ If not None, the keys should indicate the type(s) that the respective
+ formatting function applies to. Callables should return a string.
+ Types that are not specified (by their corresponding keys) are handled
+ by the default formatters. Individual types for which a formatter
+ can be set are:
+
+ - 'bool'
+ - 'int'
+ - 'timedelta' : a `numpy.timedelta64`
+ - 'datetime' : a `numpy.datetime64`
+ - 'float'
+ - 'longfloat' : 128-bit floats
+ - 'complexfloat'
+ - 'longcomplexfloat' : composed of two 128-bit floats
+ - 'void' : type `numpy.void`
+ - 'numpystr' : types `numpy.bytes_` and `numpy.str_`
+
+ Other keys that can be used to set a group of types at once are:
+
+ - 'all' : sets all types
+ - 'int_kind' : sets 'int'
+ - 'float_kind' : sets 'float' and 'longfloat'
+ - 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat'
+ - 'str_kind' : sets 'numpystr'
+ threshold : int, optional
+ Total number of array elements which trigger summarization
+ rather than full repr.
+ Defaults to ``numpy.get_printoptions()['threshold']``.
+ edgeitems : int, optional
+ Number of array items in summary at beginning and end of
+ each dimension.
+ Defaults to ``numpy.get_printoptions()['edgeitems']``.
+ sign : string, either '-', '+', or ' ', optional
+ Controls printing of the sign of floating-point types. If '+', always
+ print the sign of positive values. If ' ', always prints a space
+ (whitespace character) in the sign position of positive values. If
+ '-', omit the sign character of positive values.
+ Defaults to ``numpy.get_printoptions()['sign']``.
+
+ .. versionchanged:: 2.0
+ The sign parameter can now be an integer type, previously
+ types were floating-point types.
+
+ floatmode : str, optional
+ Controls the interpretation of the `precision` option for
+ floating-point types.
+ Defaults to ``numpy.get_printoptions()['floatmode']``.
+ Can take the following values:
+
+ - 'fixed': Always print exactly `precision` fractional digits,
+ even if this would print more or fewer digits than
+ necessary to specify the value uniquely.
+ - 'unique': Print the minimum number of fractional digits necessary
+ to represent each value uniquely. Different elements may
+ have a different number of digits. The value of the
+ `precision` option is ignored.
+ - 'maxprec': Print at most `precision` fractional digits, but if
+ an element can be uniquely represented with fewer digits
+ only print it with that many.
+ - 'maxprec_equal': Print at most `precision` fractional digits,
+ but if every element in the array can be uniquely
+ represented with an equal number of fewer digits, use that
+ many digits for all elements.
+ legacy : string or `False`, optional
+ If set to the string ``'1.13'`` enables 1.13 legacy printing mode. This
+ approximates numpy 1.13 print output by including a space in the sign
+ position of floats and different behavior for 0d arrays. If set to
+ `False`, disables legacy mode. Unrecognized strings will be ignored
+ with a warning for forward compatibility.
+
+ Returns
+ -------
+ array_str : str
+ String representation of the array.
+
+ Raises
+ ------
+ TypeError
+ if a callable in `formatter` does not return a string.
+
+ See Also
+ --------
+ array_str, array_repr, set_printoptions, get_printoptions
+
+ Notes
+ -----
+ If a formatter is specified for a certain type, the `precision` keyword is
+ ignored for that type.
+
+ This is a very flexible function; `array_repr` and `array_str` are using
+ `array2string` internally so keywords with the same name should work
+ identically in all three functions.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.array([1e-16,1,2,3])
+ >>> np.array2string(x, precision=2, separator=',',
+ ... suppress_small=True)
+ '[0.,1.,2.,3.]'
+
+ >>> x = np.arange(3.)
+ >>> np.array2string(x, formatter={'float_kind':lambda x: "%.2f" % x})
+ '[0.00 1.00 2.00]'
+
+ >>> x = np.arange(3)
+ >>> np.array2string(x, formatter={'int':lambda x: hex(x)})
+ '[0x0 0x1 0x2]'
+
+ """
+
+ overrides = _make_options_dict(precision, threshold, edgeitems,
+ max_line_width, suppress_small, None, None,
+ sign, formatter, floatmode, legacy)
+ options = format_options.get().copy()
+ options.update(overrides)
+
+ if options['legacy'] <= 113:
+ if style is np._NoValue:
+ style = repr
+
+ if a.shape == () and a.dtype.names is None:
+ return style(a.item())
+ elif style is not np._NoValue:
+ # Deprecation 11-9-2017 v1.14
+ warnings.warn("'style' argument is deprecated and no longer functional"
+ " except in 1.13 'legacy' mode",
+ DeprecationWarning, stacklevel=2)
+
+ if options['legacy'] > 113:
+ options['linewidth'] -= len(suffix)
+
+ # treat as a null array if any of shape elements == 0
+ if a.size == 0:
+ return "[]"
+
+ return _array2string(a, options, separator, prefix)
+
+
+def _extendLine(s, line, word, line_width, next_line_prefix, legacy):
+ needs_wrap = len(line) + len(word) > line_width
+ if legacy > 113:
+ # don't wrap lines if it won't help
+ if len(line) <= len(next_line_prefix):
+ needs_wrap = False
+
+ if needs_wrap:
+ s += line.rstrip() + "\n"
+ line = next_line_prefix
+ line += word
+ return s, line
+
+
+def _extendLine_pretty(s, line, word, line_width, next_line_prefix, legacy):
+ """
+ Extends line with nicely formatted (possibly multi-line) string ``word``.
+ """
+ words = word.splitlines()
+ if len(words) == 1 or legacy <= 113:
+ return _extendLine(s, line, word, line_width, next_line_prefix, legacy)
+
+ max_word_length = max(len(word) for word in words)
+ if (len(line) + max_word_length > line_width and
+ len(line) > len(next_line_prefix)):
+ s += line.rstrip() + '\n'
+ line = next_line_prefix + words[0]
+ indent = next_line_prefix
+ else:
+ indent = len(line)*' '
+ line += words[0]
+
+ for word in words[1::]:
+ s += line.rstrip() + '\n'
+ line = indent + word
+
+ suffix_length = max_word_length - len(words[-1])
+ line += suffix_length*' '
+
+ return s, line
+
+def _formatArray(a, format_function, line_width, next_line_prefix,
+ separator, edge_items, summary_insert, legacy):
+ """formatArray is designed for two modes of operation:
+
+ 1. Full output
+
+ 2. Summarized output
+
+ """
+ def recurser(index, hanging_indent, curr_width):
+ """
+ By using this local function, we don't need to recurse with all the
+ arguments. Since this function is not created recursively, the cost is
+ not significant
+ """
+ axis = len(index)
+ axes_left = a.ndim - axis
+
+ if axes_left == 0:
+ return format_function(a[index])
+
+ # when recursing, add a space to align with the [ added, and reduce the
+ # length of the line by 1
+ next_hanging_indent = hanging_indent + ' '
+ if legacy <= 113:
+ next_width = curr_width
+ else:
+ next_width = curr_width - len(']')
+
+ a_len = a.shape[axis]
+ show_summary = summary_insert and 2*edge_items < a_len
+ if show_summary:
+ leading_items = edge_items
+ trailing_items = edge_items
+ else:
+ leading_items = 0
+ trailing_items = a_len
+
+ # stringify the array with the hanging indent on the first line too
+ s = ''
+
+ # last axis (rows) - wrap elements if they would not fit on one line
+ if axes_left == 1:
+ # the length up until the beginning of the separator / bracket
+ if legacy <= 113:
+ elem_width = curr_width - len(separator.rstrip())
+ else:
+ elem_width = curr_width - max(
+ len(separator.rstrip()), len(']')
+ )
+
+ line = hanging_indent
+ for i in range(leading_items):
+ word = recurser(index + (i,), next_hanging_indent, next_width)
+ s, line = _extendLine_pretty(
+ s, line, word, elem_width, hanging_indent, legacy)
+ line += separator
+
+ if show_summary:
+ s, line = _extendLine(
+ s, line, summary_insert, elem_width, hanging_indent, legacy
+ )
+ if legacy <= 113:
+ line += ", "
+ else:
+ line += separator
+
+ for i in range(trailing_items, 1, -1):
+ word = recurser(index + (-i,), next_hanging_indent, next_width)
+ s, line = _extendLine_pretty(
+ s, line, word, elem_width, hanging_indent, legacy)
+ line += separator
+
+ if legacy <= 113:
+ # width of the separator is not considered on 1.13
+ elem_width = curr_width
+ word = recurser(index + (-1,), next_hanging_indent, next_width)
+ s, line = _extendLine_pretty(
+ s, line, word, elem_width, hanging_indent, legacy)
+
+ s += line
+
+ # other axes - insert newlines between rows
+ else:
+ s = ''
+ line_sep = separator.rstrip() + '\n'*(axes_left - 1)
+
+ for i in range(leading_items):
+ nested = recurser(
+ index + (i,), next_hanging_indent, next_width
+ )
+ s += hanging_indent + nested + line_sep
+
+ if show_summary:
+ if legacy <= 113:
+ # trailing space, fixed nbr of newlines,
+ # and fixed separator
+ s += hanging_indent + summary_insert + ", \n"
+ else:
+ s += hanging_indent + summary_insert + line_sep
+
+ for i in range(trailing_items, 1, -1):
+ nested = recurser(index + (-i,), next_hanging_indent,
+ next_width)
+ s += hanging_indent + nested + line_sep
+
+ nested = recurser(index + (-1,), next_hanging_indent, next_width)
+ s += hanging_indent + nested
+
+ # remove the hanging indent, and wrap in []
+ s = '[' + s[len(hanging_indent):] + ']'
+ return s
+
+ try:
+ # invoke the recursive part with an initial index and prefix
+ return recurser(index=(),
+ hanging_indent=next_line_prefix,
+ curr_width=line_width)
+ finally:
+ # recursive closures have a cyclic reference to themselves, which
+ # requires gc to collect (gh-10620). To avoid this problem, for
+ # performance and PyPy friendliness, we break the cycle:
+ recurser = None
+
+def _none_or_positive_arg(x, name):
+ if x is None:
+ return -1
+ if x < 0:
+ raise ValueError("{} must be >= 0".format(name))
+ return x
+
+class FloatingFormat:
+ """ Formatter for subtypes of np.floating """
+ def __init__(self, data, precision, floatmode, suppress_small, sign=False,
+ *, legacy=None):
+ # for backcompatibility, accept bools
+ if isinstance(sign, bool):
+ sign = '+' if sign else '-'
+
+ self._legacy = legacy
+ if self._legacy <= 113:
+ # when not 0d, legacy does not support '-'
+ if data.shape != () and sign == '-':
+ sign = ' '
+
+ self.floatmode = floatmode
+ if floatmode == 'unique':
+ self.precision = None
+ else:
+ self.precision = precision
+
+ self.precision = _none_or_positive_arg(self.precision, 'precision')
+
+ self.suppress_small = suppress_small
+ self.sign = sign
+ self.exp_format = False
+ self.large_exponent = False
+ self.fillFormat(data)
+
+ def fillFormat(self, data):
+ # only the finite values are used to compute the number of digits
+ finite_vals = data[isfinite(data)]
+
+ # choose exponential mode based on the non-zero finite values:
+ abs_non_zero = absolute(finite_vals[finite_vals != 0])
+ if len(abs_non_zero) != 0:
+ max_val = np.max(abs_non_zero)
+ min_val = np.min(abs_non_zero)
+ with errstate(over='ignore'): # division can overflow
+ if max_val >= 1.e8 or (not self.suppress_small and
+ (min_val < 0.0001 or max_val/min_val > 1000.)):
+ self.exp_format = True
+
+ # do a first pass of printing all the numbers, to determine sizes
+ if len(finite_vals) == 0:
+ self.pad_left = 0
+ self.pad_right = 0
+ self.trim = '.'
+ self.exp_size = -1
+ self.unique = True
+ self.min_digits = None
+ elif self.exp_format:
+ trim, unique = '.', True
+ if self.floatmode == 'fixed' or self._legacy <= 113:
+ trim, unique = 'k', False
+ strs = (dragon4_scientific(x, precision=self.precision,
+ unique=unique, trim=trim, sign=self.sign == '+')
+ for x in finite_vals)
+ frac_strs, _, exp_strs = zip(*(s.partition('e') for s in strs))
+ int_part, frac_part = zip(*(s.split('.') for s in frac_strs))
+ self.exp_size = max(len(s) for s in exp_strs) - 1
+
+ self.trim = 'k'
+ self.precision = max(len(s) for s in frac_part)
+ self.min_digits = self.precision
+ self.unique = unique
+
+ # for back-compat with np 1.13, use 2 spaces & sign and full prec
+ if self._legacy <= 113:
+ self.pad_left = 3
+ else:
+ # this should be only 1 or 2. Can be calculated from sign.
+ self.pad_left = max(len(s) for s in int_part)
+ # pad_right is only needed for nan length calculation
+ self.pad_right = self.exp_size + 2 + self.precision
+ else:
+ trim, unique = '.', True
+ if self.floatmode == 'fixed':
+ trim, unique = 'k', False
+ strs = (dragon4_positional(x, precision=self.precision,
+ fractional=True,
+ unique=unique, trim=trim,
+ sign=self.sign == '+')
+ for x in finite_vals)
+ int_part, frac_part = zip(*(s.split('.') for s in strs))
+ if self._legacy <= 113:
+ self.pad_left = 1 + max(len(s.lstrip('-+')) for s in int_part)
+ else:
+ self.pad_left = max(len(s) for s in int_part)
+ self.pad_right = max(len(s) for s in frac_part)
+ self.exp_size = -1
+ self.unique = unique
+
+ if self.floatmode in ['fixed', 'maxprec_equal']:
+ self.precision = self.min_digits = self.pad_right
+ self.trim = 'k'
+ else:
+ self.trim = '.'
+ self.min_digits = 0
+
+ if self._legacy > 113:
+ # account for sign = ' ' by adding one to pad_left
+ if self.sign == ' ' and not any(np.signbit(finite_vals)):
+ self.pad_left += 1
+
+ # if there are non-finite values, may need to increase pad_left
+ if data.size != finite_vals.size:
+ neginf = self.sign != '-' or any(data[isinf(data)] < 0)
+ offset = self.pad_right + 1 # +1 for decimal pt
+ current_options = format_options.get()
+ self.pad_left = max(
+ self.pad_left, len(current_options['nanstr']) - offset,
+ len(current_options['infstr']) + neginf - offset
+ )
+
+ def __call__(self, x):
+ if not np.isfinite(x):
+ with errstate(invalid='ignore'):
+ current_options = format_options.get()
+ if np.isnan(x):
+ sign = '+' if self.sign == '+' else ''
+ ret = sign + current_options['nanstr']
+ else: # isinf
+ sign = '-' if x < 0 else '+' if self.sign == '+' else ''
+ ret = sign + current_options['infstr']
+ return ' '*(
+ self.pad_left + self.pad_right + 1 - len(ret)
+ ) + ret
+
+ if self.exp_format:
+ return dragon4_scientific(x,
+ precision=self.precision,
+ min_digits=self.min_digits,
+ unique=self.unique,
+ trim=self.trim,
+ sign=self.sign == '+',
+ pad_left=self.pad_left,
+ exp_digits=self.exp_size)
+ else:
+ return dragon4_positional(x,
+ precision=self.precision,
+ min_digits=self.min_digits,
+ unique=self.unique,
+ fractional=True,
+ trim=self.trim,
+ sign=self.sign == '+',
+ pad_left=self.pad_left,
+ pad_right=self.pad_right)
+
+
+@set_module('numpy')
+def format_float_scientific(x, precision=None, unique=True, trim='k',
+ sign=False, pad_left=None, exp_digits=None,
+ min_digits=None):
+ """
+ Format a floating-point scalar as a decimal string in scientific notation.
+
+ Provides control over rounding, trimming and padding. Uses and assumes
+ IEEE unbiased rounding. Uses the "Dragon4" algorithm.
+
+ Parameters
+ ----------
+ x : python float or numpy floating scalar
+ Value to format.
+ precision : non-negative integer or None, optional
+ Maximum number of digits to print. May be None if `unique` is
+ `True`, but must be an integer if unique is `False`.
+ unique : boolean, optional
+ If `True`, use a digit-generation strategy which gives the shortest
+ representation which uniquely identifies the floating-point number from
+ other values of the same type, by judicious rounding. If `precision`
+ is given fewer digits than necessary can be printed. If `min_digits`
+ is given more can be printed, in which cases the last digit is rounded
+ with unbiased rounding.
+ If `False`, digits are generated as if printing an infinite-precision
+ value and stopping after `precision` digits, rounding the remaining
+ value with unbiased rounding
+ trim : one of 'k', '.', '0', '-', optional
+ Controls post-processing trimming of trailing digits, as follows:
+
+ * 'k' : keep trailing zeros, keep decimal point (no trimming)
+ * '.' : trim all trailing zeros, leave decimal point
+ * '0' : trim all but the zero before the decimal point. Insert the
+ zero if it is missing.
+ * '-' : trim trailing zeros and any trailing decimal point
+ sign : boolean, optional
+ Whether to show the sign for positive values.
+ pad_left : non-negative integer, optional
+ Pad the left side of the string with whitespace until at least that
+ many characters are to the left of the decimal point.
+ exp_digits : non-negative integer, optional
+ Pad the exponent with zeros until it contains at least this
+ many digits. If omitted, the exponent will be at least 2 digits.
+ min_digits : non-negative integer or None, optional
+ Minimum number of digits to print. This only has an effect for
+ `unique=True`. In that case more digits than necessary to uniquely
+ identify the value may be printed and rounded unbiased.
+
+ .. versionadded:: 1.21.0
+
+ Returns
+ -------
+ rep : string
+ The string representation of the floating point value
+
+ See Also
+ --------
+ format_float_positional
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.format_float_scientific(np.float32(np.pi))
+ '3.1415927e+00'
+ >>> s = np.float32(1.23e24)
+ >>> np.format_float_scientific(s, unique=False, precision=15)
+ '1.230000071797338e+24'
+ >>> np.format_float_scientific(s, exp_digits=4)
+ '1.23e+0024'
+ """
+ precision = _none_or_positive_arg(precision, 'precision')
+ pad_left = _none_or_positive_arg(pad_left, 'pad_left')
+ exp_digits = _none_or_positive_arg(exp_digits, 'exp_digits')
+ min_digits = _none_or_positive_arg(min_digits, 'min_digits')
+ if min_digits > 0 and precision > 0 and min_digits > precision:
+ raise ValueError("min_digits must be less than or equal to precision")
+ return dragon4_scientific(x, precision=precision, unique=unique,
+ trim=trim, sign=sign, pad_left=pad_left,
+ exp_digits=exp_digits, min_digits=min_digits)
+
+
+@set_module('numpy')
+def format_float_positional(x, precision=None, unique=True,
+ fractional=True, trim='k', sign=False,
+ pad_left=None, pad_right=None, min_digits=None):
+ """
+ Format a floating-point scalar as a decimal string in positional notation.
+
+ Provides control over rounding, trimming and padding. Uses and assumes
+ IEEE unbiased rounding. Uses the "Dragon4" algorithm.
+
+ Parameters
+ ----------
+ x : python float or numpy floating scalar
+ Value to format.
+ precision : non-negative integer or None, optional
+ Maximum number of digits to print. May be None if `unique` is
+ `True`, but must be an integer if unique is `False`.
+ unique : boolean, optional
+ If `True`, use a digit-generation strategy which gives the shortest
+ representation which uniquely identifies the floating-point number from
+ other values of the same type, by judicious rounding. If `precision`
+ is given fewer digits than necessary can be printed, or if `min_digits`
+ is given more can be printed, in which cases the last digit is rounded
+ with unbiased rounding.
+ If `False`, digits are generated as if printing an infinite-precision
+ value and stopping after `precision` digits, rounding the remaining
+ value with unbiased rounding
+ fractional : boolean, optional
+ If `True`, the cutoffs of `precision` and `min_digits` refer to the
+ total number of digits after the decimal point, including leading
+ zeros.
+ If `False`, `precision` and `min_digits` refer to the total number of
+ significant digits, before or after the decimal point, ignoring leading
+ zeros.
+ trim : one of 'k', '.', '0', '-', optional
+ Controls post-processing trimming of trailing digits, as follows:
+
+ * 'k' : keep trailing zeros, keep decimal point (no trimming)
+ * '.' : trim all trailing zeros, leave decimal point
+ * '0' : trim all but the zero before the decimal point. Insert the
+ zero if it is missing.
+ * '-' : trim trailing zeros and any trailing decimal point
+ sign : boolean, optional
+ Whether to show the sign for positive values.
+ pad_left : non-negative integer, optional
+ Pad the left side of the string with whitespace until at least that
+ many characters are to the left of the decimal point.
+ pad_right : non-negative integer, optional
+ Pad the right side of the string with whitespace until at least that
+ many characters are to the right of the decimal point.
+ min_digits : non-negative integer or None, optional
+ Minimum number of digits to print. Only has an effect if `unique=True`
+ in which case additional digits past those necessary to uniquely
+ identify the value may be printed, rounding the last additional digit.
+
+ .. versionadded:: 1.21.0
+
+ Returns
+ -------
+ rep : string
+ The string representation of the floating point value
+
+ See Also
+ --------
+ format_float_scientific
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.format_float_positional(np.float32(np.pi))
+ '3.1415927'
+ >>> np.format_float_positional(np.float16(np.pi))
+ '3.14'
+ >>> np.format_float_positional(np.float16(0.3))
+ '0.3'
+ >>> np.format_float_positional(np.float16(0.3), unique=False, precision=10)
+ '0.3000488281'
+ """
+ precision = _none_or_positive_arg(precision, 'precision')
+ pad_left = _none_or_positive_arg(pad_left, 'pad_left')
+ pad_right = _none_or_positive_arg(pad_right, 'pad_right')
+ min_digits = _none_or_positive_arg(min_digits, 'min_digits')
+ if not fractional and precision == 0:
+ raise ValueError("precision must be greater than 0 if "
+ "fractional=False")
+ if min_digits > 0 and precision > 0 and min_digits > precision:
+ raise ValueError("min_digits must be less than or equal to precision")
+ return dragon4_positional(x, precision=precision, unique=unique,
+ fractional=fractional, trim=trim,
+ sign=sign, pad_left=pad_left,
+ pad_right=pad_right, min_digits=min_digits)
+
+class IntegerFormat:
+ def __init__(self, data, sign='-'):
+ if data.size > 0:
+ data_max = np.max(data)
+ data_min = np.min(data)
+ data_max_str_len = len(str(data_max))
+ if sign == ' ' and data_min < 0:
+ sign = '-'
+ if data_max >= 0 and sign in "+ ":
+ data_max_str_len += 1
+ max_str_len = max(data_max_str_len,
+ len(str(data_min)))
+ else:
+ max_str_len = 0
+ self.format = f'{{:{sign}{max_str_len}d}}'
+
+ def __call__(self, x):
+ return self.format.format(x)
+
+class BoolFormat:
+ def __init__(self, data, **kwargs):
+ # add an extra space so " True" and "False" have the same length and
+ # array elements align nicely when printed, except in 0d arrays
+ self.truestr = ' True' if data.shape != () else 'True'
+
+ def __call__(self, x):
+ return self.truestr if x else "False"
+
+
+class ComplexFloatingFormat:
+ """ Formatter for subtypes of np.complexfloating """
+ def __init__(self, x, precision, floatmode, suppress_small,
+ sign=False, *, legacy=None):
+ # for backcompatibility, accept bools
+ if isinstance(sign, bool):
+ sign = '+' if sign else '-'
+
+ floatmode_real = floatmode_imag = floatmode
+ if legacy <= 113:
+ floatmode_real = 'maxprec_equal'
+ floatmode_imag = 'maxprec'
+
+ self.real_format = FloatingFormat(
+ x.real, precision, floatmode_real, suppress_small,
+ sign=sign, legacy=legacy
+ )
+ self.imag_format = FloatingFormat(
+ x.imag, precision, floatmode_imag, suppress_small,
+ sign='+', legacy=legacy
+ )
+
+ def __call__(self, x):
+ r = self.real_format(x.real)
+ i = self.imag_format(x.imag)
+
+ # add the 'j' before the terminal whitespace in i
+ sp = len(i.rstrip())
+ i = i[:sp] + 'j' + i[sp:]
+
+ return r + i
+
+
+class _TimelikeFormat:
+ def __init__(self, data):
+ non_nat = data[~isnat(data)]
+ if len(non_nat) > 0:
+ # Max str length of non-NaT elements
+ max_str_len = max(len(self._format_non_nat(np.max(non_nat))),
+ len(self._format_non_nat(np.min(non_nat))))
+ else:
+ max_str_len = 0
+ if len(non_nat) < data.size:
+ # data contains a NaT
+ max_str_len = max(max_str_len, 5)
+ self._format = '%{}s'.format(max_str_len)
+ self._nat = "'NaT'".rjust(max_str_len)
+
+ def _format_non_nat(self, x):
+ # override in subclass
+ raise NotImplementedError
+
+ def __call__(self, x):
+ if isnat(x):
+ return self._nat
+ else:
+ return self._format % self._format_non_nat(x)
+
+
+class DatetimeFormat(_TimelikeFormat):
+ def __init__(self, x, unit=None, timezone=None, casting='same_kind',
+ legacy=False):
+ # Get the unit from the dtype
+ if unit is None:
+ if x.dtype.kind == 'M':
+ unit = datetime_data(x.dtype)[0]
+ else:
+ unit = 's'
+
+ if timezone is None:
+ timezone = 'naive'
+ self.timezone = timezone
+ self.unit = unit
+ self.casting = casting
+ self.legacy = legacy
+
+ # must be called after the above are configured
+ super().__init__(x)
+
+ def __call__(self, x):
+ if self.legacy <= 113:
+ return self._format_non_nat(x)
+ return super().__call__(x)
+
+ def _format_non_nat(self, x):
+ return "'%s'" % datetime_as_string(x,
+ unit=self.unit,
+ timezone=self.timezone,
+ casting=self.casting)
+
+
+class TimedeltaFormat(_TimelikeFormat):
+ def _format_non_nat(self, x):
+ return str(x.astype('i8'))
+
+
+class SubArrayFormat:
+ def __init__(self, format_function, **options):
+ self.format_function = format_function
+ self.threshold = options['threshold']
+ self.edge_items = options['edgeitems']
+
+ def __call__(self, a):
+ self.summary_insert = "..." if a.size > self.threshold else ""
+ return self.format_array(a)
+
+ def format_array(self, a):
+ if np.ndim(a) == 0:
+ return self.format_function(a)
+
+ if self.summary_insert and a.shape[0] > 2*self.edge_items:
+ formatted = (
+ [self.format_array(a_) for a_ in a[:self.edge_items]]
+ + [self.summary_insert]
+ + [self.format_array(a_) for a_ in a[-self.edge_items:]]
+ )
+ else:
+ formatted = [self.format_array(a_) for a_ in a]
+
+ return "[" + ", ".join(formatted) + "]"
+
+
+class StructuredVoidFormat:
+ """
+ Formatter for structured np.void objects.
+
+ This does not work on structured alias types like
+ np.dtype(('i4', 'i2,i2')), as alias scalars lose their field information,
+ and the implementation relies upon np.void.__getitem__.
+ """
+ def __init__(self, format_functions):
+ self.format_functions = format_functions
+
+ @classmethod
+ def from_data(cls, data, **options):
+ """
+ This is a second way to initialize StructuredVoidFormat,
+ using the raw data as input. Added to avoid changing
+ the signature of __init__.
+ """
+ format_functions = []
+ for field_name in data.dtype.names:
+ format_function = _get_format_function(data[field_name], **options)
+ if data.dtype[field_name].shape != ():
+ format_function = SubArrayFormat(format_function, **options)
+ format_functions.append(format_function)
+ return cls(format_functions)
+
+ def __call__(self, x):
+ str_fields = [
+ format_function(field)
+ for field, format_function in zip(x, self.format_functions)
+ ]
+ if len(str_fields) == 1:
+ return "({},)".format(str_fields[0])
+ else:
+ return "({})".format(", ".join(str_fields))
+
+
+def _void_scalar_to_string(x, is_repr=True):
+ """
+ Implements the repr for structured-void scalars. It is called from the
+ scalartypes.c.src code, and is placed here because it uses the elementwise
+ formatters defined above.
+ """
+ options = format_options.get().copy()
+
+ if options["legacy"] <= 125:
+ return StructuredVoidFormat.from_data(array(x), **options)(x)
+
+ if options.get('formatter') is None:
+ options['formatter'] = {}
+ options['formatter'].setdefault('float_kind', str)
+ val_repr = StructuredVoidFormat.from_data(array(x), **options)(x)
+ if not is_repr:
+ return val_repr
+ cls = type(x)
+ cls_fqn = cls.__module__.replace("numpy", "np") + "." + cls.__name__
+ void_dtype = np.dtype((np.void, x.dtype))
+ return f"{cls_fqn}({val_repr}, dtype={void_dtype!s})"
+
+
+_typelessdata = [int_, float64, complex128, _nt.bool]
+
+
+def dtype_is_implied(dtype):
+ """
+ Determine if the given dtype is implied by the representation
+ of its values.
+
+ Parameters
+ ----------
+ dtype : dtype
+ Data type
+
+ Returns
+ -------
+ implied : bool
+ True if the dtype is implied by the representation of its values.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np._core.arrayprint.dtype_is_implied(int)
+ True
+ >>> np.array([1, 2, 3], int)
+ array([1, 2, 3])
+ >>> np._core.arrayprint.dtype_is_implied(np.int8)
+ False
+ >>> np.array([1, 2, 3], np.int8)
+ array([1, 2, 3], dtype=int8)
+ """
+ dtype = np.dtype(dtype)
+ if format_options.get()['legacy'] <= 113 and dtype.type == np.bool:
+ return False
+
+ # not just void types can be structured, and names are not part of the repr
+ if dtype.names is not None:
+ return False
+
+ # should care about endianness *unless size is 1* (e.g., int8, bool)
+ if not dtype.isnative:
+ return False
+
+ return dtype.type in _typelessdata
+
+
+def dtype_short_repr(dtype):
+ """
+ Convert a dtype to a short form which evaluates to the same dtype.
+
+ The intent is roughly that the following holds
+
+ >>> from numpy import *
+ >>> dt = np.int64([1, 2]).dtype
+ >>> assert eval(dtype_short_repr(dt)) == dt
+ """
+ if type(dtype).__repr__ != np.dtype.__repr__:
+ # TODO: Custom repr for user DTypes, logic should likely move.
+ return repr(dtype)
+ if dtype.names is not None:
+ # structured dtypes give a list or tuple repr
+ return str(dtype)
+ elif issubclass(dtype.type, flexible):
+ # handle these separately so they don't give garbage like str256
+ return "'%s'" % str(dtype)
+
+ typename = dtype.name
+ if not dtype.isnative:
+ # deal with cases like dtype(' 210
+ and arr.size > current_options['threshold']):
+ extras.append(f"shape={arr.shape}")
+ if not dtype_is_implied(arr.dtype) or arr.size == 0:
+ extras.append(f"dtype={dtype_short_repr(arr.dtype)}")
+
+ if not extras:
+ return prefix + lst + ")"
+
+ arr_str = prefix + lst + ","
+ extra_str = ", ".join(extras) + ")"
+ # compute whether we should put extras on a new line: Do so if adding the
+ # extras would extend the last line past max_line_width.
+ # Note: This line gives the correct result even when rfind returns -1.
+ last_line_len = len(arr_str) - (arr_str.rfind('\n') + 1)
+ spacer = " "
+ if current_options['legacy'] <= 113:
+ if issubclass(arr.dtype.type, flexible):
+ spacer = '\n' + ' '*len(prefix)
+ elif last_line_len + len(extra_str) + 1 > max_line_width:
+ spacer = '\n' + ' '*len(prefix)
+
+ return arr_str + spacer + extra_str
+
+
+def _array_repr_dispatcher(
+ arr, max_line_width=None, precision=None, suppress_small=None):
+ return (arr,)
+
+
+@array_function_dispatch(_array_repr_dispatcher, module='numpy')
+def array_repr(arr, max_line_width=None, precision=None, suppress_small=None):
+ """
+ Return the string representation of an array.
+
+ Parameters
+ ----------
+ arr : ndarray
+ Input array.
+ max_line_width : int, optional
+ Inserts newlines if text is longer than `max_line_width`.
+ Defaults to ``numpy.get_printoptions()['linewidth']``.
+ precision : int, optional
+ Floating point precision.
+ Defaults to ``numpy.get_printoptions()['precision']``.
+ suppress_small : bool, optional
+ Represent numbers "very close" to zero as zero; default is False.
+ Very close is defined by precision: if the precision is 8, e.g.,
+ numbers smaller (in absolute value) than 5e-9 are represented as
+ zero.
+ Defaults to ``numpy.get_printoptions()['suppress']``.
+
+ Returns
+ -------
+ string : str
+ The string representation of an array.
+
+ See Also
+ --------
+ array_str, array2string, set_printoptions
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.array_repr(np.array([1,2]))
+ 'array([1, 2])'
+ >>> np.array_repr(np.ma.array([0.]))
+ 'MaskedArray([0.])'
+ >>> np.array_repr(np.array([], np.int32))
+ 'array([], dtype=int32)'
+
+ >>> x = np.array([1e-6, 4e-7, 2, 3])
+ >>> np.array_repr(x, precision=6, suppress_small=True)
+ 'array([0.000001, 0. , 2. , 3. ])'
+
+ """
+ return _array_repr_implementation(
+ arr, max_line_width, precision, suppress_small)
+
+
+@_recursive_guard()
+def _guarded_repr_or_str(v):
+ if isinstance(v, bytes):
+ return repr(v)
+ return str(v)
+
+
+def _array_str_implementation(
+ a, max_line_width=None, precision=None, suppress_small=None,
+ array2string=array2string):
+ """Internal version of array_str() that allows overriding array2string."""
+ if (format_options.get()['legacy'] <= 113 and
+ a.shape == () and not a.dtype.names):
+ return str(a.item())
+
+ # the str of 0d arrays is a special case: It should appear like a scalar,
+ # so floats are not truncated by `precision`, and strings are not wrapped
+ # in quotes. So we return the str of the scalar value.
+ if a.shape == ():
+ # obtain a scalar and call str on it, avoiding problems for subclasses
+ # for which indexing with () returns a 0d instead of a scalar by using
+ # ndarray's getindex. Also guard against recursive 0d object arrays.
+ return _guarded_repr_or_str(np.ndarray.__getitem__(a, ()))
+
+ return array2string(a, max_line_width, precision, suppress_small, ' ', "")
+
+
+def _array_str_dispatcher(
+ a, max_line_width=None, precision=None, suppress_small=None):
+ return (a,)
+
+
+@array_function_dispatch(_array_str_dispatcher, module='numpy')
+def array_str(a, max_line_width=None, precision=None, suppress_small=None):
+ """
+ Return a string representation of the data in an array.
+
+ The data in the array is returned as a single string. This function is
+ similar to `array_repr`, the difference being that `array_repr` also
+ returns information on the kind of array and its data type.
+
+ Parameters
+ ----------
+ a : ndarray
+ Input array.
+ max_line_width : int, optional
+ Inserts newlines if text is longer than `max_line_width`.
+ Defaults to ``numpy.get_printoptions()['linewidth']``.
+ precision : int, optional
+ Floating point precision.
+ Defaults to ``numpy.get_printoptions()['precision']``.
+ suppress_small : bool, optional
+ Represent numbers "very close" to zero as zero; default is False.
+ Very close is defined by precision: if the precision is 8, e.g.,
+ numbers smaller (in absolute value) than 5e-9 are represented as
+ zero.
+ Defaults to ``numpy.get_printoptions()['suppress']``.
+
+ See Also
+ --------
+ array2string, array_repr, set_printoptions
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.array_str(np.arange(3))
+ '[0 1 2]'
+
+ """
+ return _array_str_implementation(
+ a, max_line_width, precision, suppress_small)
+
+
+# needed if __array_function__ is disabled
+_array2string_impl = getattr(array2string, '__wrapped__', array2string)
+_default_array_str = functools.partial(_array_str_implementation,
+ array2string=_array2string_impl)
+_default_array_repr = functools.partial(_array_repr_implementation,
+ array2string=_array2string_impl)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/arrayprint.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/arrayprint.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..1f8be64d5e7ba36d5b60e26f2101d9c3838f1ed3
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/arrayprint.pyi
@@ -0,0 +1,229 @@
+from collections.abc import Callable
+
+# Using a private class is by no means ideal, but it is simply a consequence
+# of a `contextlib.context` returning an instance of aforementioned class
+from contextlib import _GeneratorContextManager
+from typing import Any, Final, Literal, SupportsIndex, TypeAlias, TypedDict, overload, type_check_only
+
+from typing_extensions import deprecated
+
+import numpy as np
+from numpy._globals import _NoValueType
+from numpy._typing import NDArray, _CharLike_co, _FloatLike_co
+
+__all__ = [
+ "array2string",
+ "array_repr",
+ "array_str",
+ "format_float_positional",
+ "format_float_scientific",
+ "get_printoptions",
+ "printoptions",
+ "set_printoptions",
+]
+
+###
+
+_FloatMode: TypeAlias = Literal["fixed", "unique", "maxprec", "maxprec_equal"]
+_LegacyNoStyle: TypeAlias = Literal["1.21", "1.25", "2.1", False]
+_Legacy: TypeAlias = Literal["1.13", _LegacyNoStyle]
+_Sign: TypeAlias = Literal["-", "+", " "]
+_Trim: TypeAlias = Literal["k", ".", "0", "-"]
+_ReprFunc: TypeAlias = Callable[[NDArray[Any]], str]
+
+@type_check_only
+class _FormatDict(TypedDict, total=False):
+ bool: Callable[[np.bool], str]
+ int: Callable[[np.integer], str]
+ timedelta: Callable[[np.timedelta64], str]
+ datetime: Callable[[np.datetime64], str]
+ float: Callable[[np.floating], str]
+ longfloat: Callable[[np.longdouble], str]
+ complexfloat: Callable[[np.complexfloating], str]
+ longcomplexfloat: Callable[[np.clongdouble], str]
+ void: Callable[[np.void], str]
+ numpystr: Callable[[_CharLike_co], str]
+ object: Callable[[object], str]
+ all: Callable[[object], str]
+ int_kind: Callable[[np.integer], str]
+ float_kind: Callable[[np.floating], str]
+ complex_kind: Callable[[np.complexfloating], str]
+ str_kind: Callable[[_CharLike_co], str]
+
+@type_check_only
+class _FormatOptions(TypedDict):
+ precision: int
+ threshold: int
+ edgeitems: int
+ linewidth: int
+ suppress: bool
+ nanstr: str
+ infstr: str
+ formatter: _FormatDict | None
+ sign: _Sign
+ floatmode: _FloatMode
+ legacy: _Legacy
+
+###
+
+__docformat__: Final = "restructuredtext" # undocumented
+
+def set_printoptions(
+ precision: None | SupportsIndex = ...,
+ threshold: None | int = ...,
+ edgeitems: None | int = ...,
+ linewidth: None | int = ...,
+ suppress: None | bool = ...,
+ nanstr: None | str = ...,
+ infstr: None | str = ...,
+ formatter: None | _FormatDict = ...,
+ sign: _Sign | None = None,
+ floatmode: _FloatMode | None = None,
+ *,
+ legacy: _Legacy | None = None,
+ override_repr: _ReprFunc | None = None,
+) -> None: ...
+def get_printoptions() -> _FormatOptions: ...
+
+# public numpy export
+@overload # no style
+def array2string(
+ a: NDArray[Any],
+ max_line_width: int | None = None,
+ precision: SupportsIndex | None = None,
+ suppress_small: bool | None = None,
+ separator: str = " ",
+ prefix: str = "",
+ style: _NoValueType = ...,
+ formatter: _FormatDict | None = None,
+ threshold: int | None = None,
+ edgeitems: int | None = None,
+ sign: _Sign | None = None,
+ floatmode: _FloatMode | None = None,
+ suffix: str = "",
+ *,
+ legacy: _Legacy | None = None,
+) -> str: ...
+@overload # style= (positional), legacy="1.13"
+def array2string(
+ a: NDArray[Any],
+ max_line_width: int | None,
+ precision: SupportsIndex | None,
+ suppress_small: bool | None,
+ separator: str,
+ prefix: str,
+ style: _ReprFunc,
+ formatter: _FormatDict | None = None,
+ threshold: int | None = None,
+ edgeitems: int | None = None,
+ sign: _Sign | None = None,
+ floatmode: _FloatMode | None = None,
+ suffix: str = "",
+ *,
+ legacy: Literal["1.13"],
+) -> str: ...
+@overload # style= (keyword), legacy="1.13"
+def array2string(
+ a: NDArray[Any],
+ max_line_width: int | None = None,
+ precision: SupportsIndex | None = None,
+ suppress_small: bool | None = None,
+ separator: str = " ",
+ prefix: str = "",
+ *,
+ style: _ReprFunc,
+ formatter: _FormatDict | None = None,
+ threshold: int | None = None,
+ edgeitems: int | None = None,
+ sign: _Sign | None = None,
+ floatmode: _FloatMode | None = None,
+ suffix: str = "",
+ legacy: Literal["1.13"],
+) -> str: ...
+@overload # style= (positional), legacy!="1.13"
+@deprecated("'style' argument is deprecated and no longer functional except in 1.13 'legacy' mode")
+def array2string(
+ a: NDArray[Any],
+ max_line_width: int | None,
+ precision: SupportsIndex | None,
+ suppress_small: bool | None,
+ separator: str,
+ prefix: str,
+ style: _ReprFunc,
+ formatter: _FormatDict | None = None,
+ threshold: int | None = None,
+ edgeitems: int | None = None,
+ sign: _Sign | None = None,
+ floatmode: _FloatMode | None = None,
+ suffix: str = "",
+ *,
+ legacy: _LegacyNoStyle | None = None,
+) -> str: ...
+@overload # style= (keyword), legacy="1.13"
+@deprecated("'style' argument is deprecated and no longer functional except in 1.13 'legacy' mode")
+def array2string(
+ a: NDArray[Any],
+ max_line_width: int | None = None,
+ precision: SupportsIndex | None = None,
+ suppress_small: bool | None = None,
+ separator: str = " ",
+ prefix: str = "",
+ *,
+ style: _ReprFunc,
+ formatter: _FormatDict | None = None,
+ threshold: int | None = None,
+ edgeitems: int | None = None,
+ sign: _Sign | None = None,
+ floatmode: _FloatMode | None = None,
+ suffix: str = "",
+ legacy: _LegacyNoStyle | None = None,
+) -> str: ...
+
+def format_float_scientific(
+ x: _FloatLike_co,
+ precision: None | int = ...,
+ unique: bool = ...,
+ trim: _Trim = "k",
+ sign: bool = ...,
+ pad_left: None | int = ...,
+ exp_digits: None | int = ...,
+ min_digits: None | int = ...,
+) -> str: ...
+def format_float_positional(
+ x: _FloatLike_co,
+ precision: None | int = ...,
+ unique: bool = ...,
+ fractional: bool = ...,
+ trim: _Trim = "k",
+ sign: bool = ...,
+ pad_left: None | int = ...,
+ pad_right: None | int = ...,
+ min_digits: None | int = ...,
+) -> str: ...
+def array_repr(
+ arr: NDArray[Any],
+ max_line_width: None | int = ...,
+ precision: None | SupportsIndex = ...,
+ suppress_small: None | bool = ...,
+) -> str: ...
+def array_str(
+ a: NDArray[Any],
+ max_line_width: None | int = ...,
+ precision: None | SupportsIndex = ...,
+ suppress_small: None | bool = ...,
+) -> str: ...
+def printoptions(
+ precision: None | SupportsIndex = ...,
+ threshold: None | int = ...,
+ edgeitems: None | int = ...,
+ linewidth: None | int = ...,
+ suppress: None | bool = ...,
+ nanstr: None | str = ...,
+ infstr: None | str = ...,
+ formatter: None | _FormatDict = ...,
+ sign: None | _Sign = None,
+ floatmode: _FloatMode | None = None,
+ *,
+ legacy: _Legacy | None = None,
+ override_repr: _ReprFunc | None = None,
+) -> _GeneratorContextManager[_FormatOptions]: ...
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/cversions.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/cversions.py
new file mode 100644
index 0000000000000000000000000000000000000000..00159c3a8031d8ccd44b226db42090f97014cd9f
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/cversions.py
@@ -0,0 +1,13 @@
+"""Simple script to compute the api hash of the current API.
+
+The API has is defined by numpy_api_order and ufunc_api_order.
+
+"""
+from os.path import dirname
+
+from code_generators.genapi import fullapi_hash
+from code_generators.numpy_api import full_api
+
+if __name__ == '__main__':
+ curdir = dirname(__file__)
+ print(fullapi_hash(full_api))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/defchararray.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/defchararray.py
new file mode 100644
index 0000000000000000000000000000000000000000..49ed5d38525e91401241b2759e00e5ab18d0c606
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/defchararray.py
@@ -0,0 +1,1414 @@
+"""
+This module contains a set of functions for vectorized string
+operations and methods.
+
+.. note::
+ The `chararray` class exists for backwards compatibility with
+ Numarray, it is not recommended for new development. Starting from numpy
+ 1.4, if one needs arrays of strings, it is recommended to use arrays of
+ `dtype` `object_`, `bytes_` or `str_`, and use the free functions
+ in the `numpy.char` module for fast vectorized string operations.
+
+Some methods will only be available if the corresponding string method is
+available in your version of Python.
+
+The preferred alias for `defchararray` is `numpy.char`.
+
+"""
+import functools
+
+import numpy as np
+from .._utils import set_module
+from .numerictypes import bytes_, str_, character
+from .numeric import ndarray, array as narray, asarray as asnarray
+from numpy._core.multiarray import compare_chararrays
+from numpy._core import overrides
+from numpy.strings import *
+from numpy.strings import (
+ multiply as strings_multiply,
+ partition as strings_partition,
+ rpartition as strings_rpartition,
+)
+from numpy._core.strings import (
+ _split as split,
+ _rsplit as rsplit,
+ _splitlines as splitlines,
+ _join as join,
+)
+
+__all__ = [
+ 'equal', 'not_equal', 'greater_equal', 'less_equal',
+ 'greater', 'less', 'str_len', 'add', 'multiply', 'mod', 'capitalize',
+ 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs',
+ 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace',
+ 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition',
+ 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit',
+ 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase',
+ 'title', 'translate', 'upper', 'zfill', 'isnumeric', 'isdecimal',
+ 'array', 'asarray', 'compare_chararrays', 'chararray'
+ ]
+
+
+array_function_dispatch = functools.partial(
+ overrides.array_function_dispatch, module='numpy.char')
+
+
+def _binary_op_dispatcher(x1, x2):
+ return (x1, x2)
+
+
+@array_function_dispatch(_binary_op_dispatcher)
+def equal(x1, x2):
+ """
+ Return (x1 == x2) element-wise.
+
+ Unlike `numpy.equal`, this comparison is performed by first
+ stripping whitespace characters from the end of the string. This
+ behavior is provided for backward-compatibility with numarray.
+
+ Parameters
+ ----------
+ x1, x2 : array_like of str or unicode
+ Input arrays of the same shape.
+
+ Returns
+ -------
+ out : ndarray
+ Output array of bools.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> y = "aa "
+ >>> x = "aa"
+ >>> np.char.equal(x, y)
+ array(True)
+
+ See Also
+ --------
+ not_equal, greater_equal, less_equal, greater, less
+ """
+ return compare_chararrays(x1, x2, '==', True)
+
+
+@array_function_dispatch(_binary_op_dispatcher)
+def not_equal(x1, x2):
+ """
+ Return (x1 != x2) element-wise.
+
+ Unlike `numpy.not_equal`, this comparison is performed by first
+ stripping whitespace characters from the end of the string. This
+ behavior is provided for backward-compatibility with numarray.
+
+ Parameters
+ ----------
+ x1, x2 : array_like of str or unicode
+ Input arrays of the same shape.
+
+ Returns
+ -------
+ out : ndarray
+ Output array of bools.
+
+ See Also
+ --------
+ equal, greater_equal, less_equal, greater, less
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x1 = np.array(['a', 'b', 'c'])
+ >>> np.char.not_equal(x1, 'b')
+ array([ True, False, True])
+
+ """
+ return compare_chararrays(x1, x2, '!=', True)
+
+
+@array_function_dispatch(_binary_op_dispatcher)
+def greater_equal(x1, x2):
+ """
+ Return (x1 >= x2) element-wise.
+
+ Unlike `numpy.greater_equal`, this comparison is performed by
+ first stripping whitespace characters from the end of the string.
+ This behavior is provided for backward-compatibility with
+ numarray.
+
+ Parameters
+ ----------
+ x1, x2 : array_like of str or unicode
+ Input arrays of the same shape.
+
+ Returns
+ -------
+ out : ndarray
+ Output array of bools.
+
+ See Also
+ --------
+ equal, not_equal, less_equal, greater, less
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x1 = np.array(['a', 'b', 'c'])
+ >>> np.char.greater_equal(x1, 'b')
+ array([False, True, True])
+
+ """
+ return compare_chararrays(x1, x2, '>=', True)
+
+
+@array_function_dispatch(_binary_op_dispatcher)
+def less_equal(x1, x2):
+ """
+ Return (x1 <= x2) element-wise.
+
+ Unlike `numpy.less_equal`, this comparison is performed by first
+ stripping whitespace characters from the end of the string. This
+ behavior is provided for backward-compatibility with numarray.
+
+ Parameters
+ ----------
+ x1, x2 : array_like of str or unicode
+ Input arrays of the same shape.
+
+ Returns
+ -------
+ out : ndarray
+ Output array of bools.
+
+ See Also
+ --------
+ equal, not_equal, greater_equal, greater, less
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x1 = np.array(['a', 'b', 'c'])
+ >>> np.char.less_equal(x1, 'b')
+ array([ True, True, False])
+
+ """
+ return compare_chararrays(x1, x2, '<=', True)
+
+
+@array_function_dispatch(_binary_op_dispatcher)
+def greater(x1, x2):
+ """
+ Return (x1 > x2) element-wise.
+
+ Unlike `numpy.greater`, this comparison is performed by first
+ stripping whitespace characters from the end of the string. This
+ behavior is provided for backward-compatibility with numarray.
+
+ Parameters
+ ----------
+ x1, x2 : array_like of str or unicode
+ Input arrays of the same shape.
+
+ Returns
+ -------
+ out : ndarray
+ Output array of bools.
+
+ See Also
+ --------
+ equal, not_equal, greater_equal, less_equal, less
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x1 = np.array(['a', 'b', 'c'])
+ >>> np.char.greater(x1, 'b')
+ array([False, False, True])
+
+ """
+ return compare_chararrays(x1, x2, '>', True)
+
+
+@array_function_dispatch(_binary_op_dispatcher)
+def less(x1, x2):
+ """
+ Return (x1 < x2) element-wise.
+
+ Unlike `numpy.greater`, this comparison is performed by first
+ stripping whitespace characters from the end of the string. This
+ behavior is provided for backward-compatibility with numarray.
+
+ Parameters
+ ----------
+ x1, x2 : array_like of str or unicode
+ Input arrays of the same shape.
+
+ Returns
+ -------
+ out : ndarray
+ Output array of bools.
+
+ See Also
+ --------
+ equal, not_equal, greater_equal, less_equal, greater
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x1 = np.array(['a', 'b', 'c'])
+ >>> np.char.less(x1, 'b')
+ array([True, False, False])
+
+ """
+ return compare_chararrays(x1, x2, '<', True)
+
+
+@set_module("numpy.char")
+def multiply(a, i):
+ """
+ Return (a * i), that is string multiple concatenation,
+ element-wise.
+
+ Values in ``i`` of less than 0 are treated as 0 (which yields an
+ empty string).
+
+ Parameters
+ ----------
+ a : array_like, with `np.bytes_` or `np.str_` dtype
+
+ i : array_like, with any integer dtype
+
+ Returns
+ -------
+ out : ndarray
+ Output array of str or unicode, depending on input types
+
+ Notes
+ -----
+ This is a thin wrapper around np.strings.multiply that raises
+ `ValueError` when ``i`` is not an integer. It only
+ exists for backwards-compatibility.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array(["a", "b", "c"])
+ >>> np.strings.multiply(a, 3)
+ array(['aaa', 'bbb', 'ccc'], dtype='>> i = np.array([1, 2, 3])
+ >>> np.strings.multiply(a, i)
+ array(['a', 'bb', 'ccc'], dtype='>> np.strings.multiply(np.array(['a']), i)
+ array(['a', 'aa', 'aaa'], dtype='>> a = np.array(['a', 'b', 'c', 'd', 'e', 'f']).reshape((2, 3))
+ >>> np.strings.multiply(a, 3)
+ array([['aaa', 'bbb', 'ccc'],
+ ['ddd', 'eee', 'fff']], dtype='>> np.strings.multiply(a, i)
+ array([['a', 'bb', 'ccc'],
+ ['d', 'ee', 'fff']], dtype='>> import numpy as np
+ >>> x = np.array(["Numpy is nice!"])
+ >>> np.char.partition(x, " ")
+ array([['Numpy', ' ', 'is nice!']], dtype='>> import numpy as np
+ >>> a = np.array(['aAaAaA', ' aA ', 'abBABba'])
+ >>> np.char.rpartition(a, 'A')
+ array([['aAaAa', 'A', ''],
+ [' a', 'A', ' '],
+ ['abB', 'A', 'Bba']], dtype='= 2`` and ``order='F'``, in which case `strides`
+ is in "Fortran order".
+
+ Methods
+ -------
+ astype
+ argsort
+ copy
+ count
+ decode
+ dump
+ dumps
+ encode
+ endswith
+ expandtabs
+ fill
+ find
+ flatten
+ getfield
+ index
+ isalnum
+ isalpha
+ isdecimal
+ isdigit
+ islower
+ isnumeric
+ isspace
+ istitle
+ isupper
+ item
+ join
+ ljust
+ lower
+ lstrip
+ nonzero
+ put
+ ravel
+ repeat
+ replace
+ reshape
+ resize
+ rfind
+ rindex
+ rjust
+ rsplit
+ rstrip
+ searchsorted
+ setfield
+ setflags
+ sort
+ split
+ splitlines
+ squeeze
+ startswith
+ strip
+ swapaxes
+ swapcase
+ take
+ title
+ tofile
+ tolist
+ tostring
+ translate
+ transpose
+ upper
+ view
+ zfill
+
+ Parameters
+ ----------
+ shape : tuple
+ Shape of the array.
+ itemsize : int, optional
+ Length of each array element, in number of characters. Default is 1.
+ unicode : bool, optional
+ Are the array elements of type unicode (True) or string (False).
+ Default is False.
+ buffer : object exposing the buffer interface or str, optional
+ Memory address of the start of the array data. Default is None,
+ in which case a new array is created.
+ offset : int, optional
+ Fixed stride displacement from the beginning of an axis?
+ Default is 0. Needs to be >=0.
+ strides : array_like of ints, optional
+ Strides for the array (see `~numpy.ndarray.strides` for
+ full description). Default is None.
+ order : {'C', 'F'}, optional
+ The order in which the array data is stored in memory: 'C' ->
+ "row major" order (the default), 'F' -> "column major"
+ (Fortran) order.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> charar = np.char.chararray((3, 3))
+ >>> charar[:] = 'a'
+ >>> charar
+ chararray([[b'a', b'a', b'a'],
+ [b'a', b'a', b'a'],
+ [b'a', b'a', b'a']], dtype='|S1')
+
+ >>> charar = np.char.chararray(charar.shape, itemsize=5)
+ >>> charar[:] = 'abc'
+ >>> charar
+ chararray([[b'abc', b'abc', b'abc'],
+ [b'abc', b'abc', b'abc'],
+ [b'abc', b'abc', b'abc']], dtype='|S5')
+
+ """
+ def __new__(subtype, shape, itemsize=1, unicode=False, buffer=None,
+ offset=0, strides=None, order='C'):
+ if unicode:
+ dtype = str_
+ else:
+ dtype = bytes_
+
+ # force itemsize to be a Python int, since using NumPy integer
+ # types results in itemsize.itemsize being used as the size of
+ # strings in the new array.
+ itemsize = int(itemsize)
+
+ if isinstance(buffer, str):
+ # unicode objects do not have the buffer interface
+ filler = buffer
+ buffer = None
+ else:
+ filler = None
+
+ if buffer is None:
+ self = ndarray.__new__(subtype, shape, (dtype, itemsize),
+ order=order)
+ else:
+ self = ndarray.__new__(subtype, shape, (dtype, itemsize),
+ buffer=buffer,
+ offset=offset, strides=strides,
+ order=order)
+ if filler is not None:
+ self[...] = filler
+
+ return self
+
+ def __array_wrap__(self, arr, context=None, return_scalar=False):
+ # When calling a ufunc (and some other functions), we return a
+ # chararray if the ufunc output is a string-like array,
+ # or an ndarray otherwise
+ if arr.dtype.char in "SUbc":
+ return arr.view(type(self))
+ return arr
+
+ def __array_finalize__(self, obj):
+ # The b is a special case because it is used for reconstructing.
+ if self.dtype.char not in 'VSUbc':
+ raise ValueError("Can only create a chararray from string data.")
+
+ def __getitem__(self, obj):
+ val = ndarray.__getitem__(self, obj)
+ if isinstance(val, character):
+ return val.rstrip()
+ return val
+
+ # IMPLEMENTATION NOTE: Most of the methods of this class are
+ # direct delegations to the free functions in this module.
+ # However, those that return an array of strings should instead
+ # return a chararray, so some extra wrapping is required.
+
+ def __eq__(self, other):
+ """
+ Return (self == other) element-wise.
+
+ See Also
+ --------
+ equal
+ """
+ return equal(self, other)
+
+ def __ne__(self, other):
+ """
+ Return (self != other) element-wise.
+
+ See Also
+ --------
+ not_equal
+ """
+ return not_equal(self, other)
+
+ def __ge__(self, other):
+ """
+ Return (self >= other) element-wise.
+
+ See Also
+ --------
+ greater_equal
+ """
+ return greater_equal(self, other)
+
+ def __le__(self, other):
+ """
+ Return (self <= other) element-wise.
+
+ See Also
+ --------
+ less_equal
+ """
+ return less_equal(self, other)
+
+ def __gt__(self, other):
+ """
+ Return (self > other) element-wise.
+
+ See Also
+ --------
+ greater
+ """
+ return greater(self, other)
+
+ def __lt__(self, other):
+ """
+ Return (self < other) element-wise.
+
+ See Also
+ --------
+ less
+ """
+ return less(self, other)
+
+ def __add__(self, other):
+ """
+ Return (self + other), that is string concatenation,
+ element-wise for a pair of array_likes of str or unicode.
+
+ See Also
+ --------
+ add
+ """
+ return add(self, other)
+
+ def __radd__(self, other):
+ """
+ Return (other + self), that is string concatenation,
+ element-wise for a pair of array_likes of `bytes_` or `str_`.
+
+ See Also
+ --------
+ add
+ """
+ return add(other, self)
+
+ def __mul__(self, i):
+ """
+ Return (self * i), that is string multiple concatenation,
+ element-wise.
+
+ See Also
+ --------
+ multiply
+ """
+ return asarray(multiply(self, i))
+
+ def __rmul__(self, i):
+ """
+ Return (self * i), that is string multiple concatenation,
+ element-wise.
+
+ See Also
+ --------
+ multiply
+ """
+ return asarray(multiply(self, i))
+
+ def __mod__(self, i):
+ """
+ Return (self % i), that is pre-Python 2.6 string formatting
+ (interpolation), element-wise for a pair of array_likes of `bytes_`
+ or `str_`.
+
+ See Also
+ --------
+ mod
+ """
+ return asarray(mod(self, i))
+
+ def __rmod__(self, other):
+ return NotImplemented
+
+ def argsort(self, axis=-1, kind=None, order=None):
+ """
+ Return the indices that sort the array lexicographically.
+
+ For full documentation see `numpy.argsort`, for which this method is
+ in fact merely a "thin wrapper."
+
+ Examples
+ --------
+ >>> c = np.array(['a1b c', '1b ca', 'b ca1', 'Ca1b'], 'S5')
+ >>> c = c.view(np.char.chararray); c
+ chararray(['a1b c', '1b ca', 'b ca1', 'Ca1b'],
+ dtype='|S5')
+ >>> c[c.argsort()]
+ chararray(['1b ca', 'Ca1b', 'a1b c', 'b ca1'],
+ dtype='|S5')
+
+ """
+ return self.__array__().argsort(axis, kind, order)
+ argsort.__doc__ = ndarray.argsort.__doc__
+
+ def capitalize(self):
+ """
+ Return a copy of `self` with only the first character of each element
+ capitalized.
+
+ See Also
+ --------
+ char.capitalize
+
+ """
+ return asarray(capitalize(self))
+
+ def center(self, width, fillchar=' '):
+ """
+ Return a copy of `self` with its elements centered in a
+ string of length `width`.
+
+ See Also
+ --------
+ center
+ """
+ return asarray(center(self, width, fillchar))
+
+ def count(self, sub, start=0, end=None):
+ """
+ Returns an array with the number of non-overlapping occurrences of
+ substring `sub` in the range [`start`, `end`].
+
+ See Also
+ --------
+ char.count
+
+ """
+ return count(self, sub, start, end)
+
+ def decode(self, encoding=None, errors=None):
+ """
+ Calls ``bytes.decode`` element-wise.
+
+ See Also
+ --------
+ char.decode
+
+ """
+ return decode(self, encoding, errors)
+
+ def encode(self, encoding=None, errors=None):
+ """
+ Calls :meth:`str.encode` element-wise.
+
+ See Also
+ --------
+ char.encode
+
+ """
+ return encode(self, encoding, errors)
+
+ def endswith(self, suffix, start=0, end=None):
+ """
+ Returns a boolean array which is `True` where the string element
+ in `self` ends with `suffix`, otherwise `False`.
+
+ See Also
+ --------
+ char.endswith
+
+ """
+ return endswith(self, suffix, start, end)
+
+ def expandtabs(self, tabsize=8):
+ """
+ Return a copy of each string element where all tab characters are
+ replaced by one or more spaces.
+
+ See Also
+ --------
+ char.expandtabs
+
+ """
+ return asarray(expandtabs(self, tabsize))
+
+ def find(self, sub, start=0, end=None):
+ """
+ For each element, return the lowest index in the string where
+ substring `sub` is found.
+
+ See Also
+ --------
+ char.find
+
+ """
+ return find(self, sub, start, end)
+
+ def index(self, sub, start=0, end=None):
+ """
+ Like `find`, but raises :exc:`ValueError` when the substring is not
+ found.
+
+ See Also
+ --------
+ char.index
+
+ """
+ return index(self, sub, start, end)
+
+ def isalnum(self):
+ """
+ Returns true for each element if all characters in the string
+ are alphanumeric and there is at least one character, false
+ otherwise.
+
+ See Also
+ --------
+ char.isalnum
+
+ """
+ return isalnum(self)
+
+ def isalpha(self):
+ """
+ Returns true for each element if all characters in the string
+ are alphabetic and there is at least one character, false
+ otherwise.
+
+ See Also
+ --------
+ char.isalpha
+
+ """
+ return isalpha(self)
+
+ def isdigit(self):
+ """
+ Returns true for each element if all characters in the string are
+ digits and there is at least one character, false otherwise.
+
+ See Also
+ --------
+ char.isdigit
+
+ """
+ return isdigit(self)
+
+ def islower(self):
+ """
+ Returns true for each element if all cased characters in the
+ string are lowercase and there is at least one cased character,
+ false otherwise.
+
+ See Also
+ --------
+ char.islower
+
+ """
+ return islower(self)
+
+ def isspace(self):
+ """
+ Returns true for each element if there are only whitespace
+ characters in the string and there is at least one character,
+ false otherwise.
+
+ See Also
+ --------
+ char.isspace
+
+ """
+ return isspace(self)
+
+ def istitle(self):
+ """
+ Returns true for each element if the element is a titlecased
+ string and there is at least one character, false otherwise.
+
+ See Also
+ --------
+ char.istitle
+
+ """
+ return istitle(self)
+
+ def isupper(self):
+ """
+ Returns true for each element if all cased characters in the
+ string are uppercase and there is at least one character, false
+ otherwise.
+
+ See Also
+ --------
+ char.isupper
+
+ """
+ return isupper(self)
+
+ def join(self, seq):
+ """
+ Return a string which is the concatenation of the strings in the
+ sequence `seq`.
+
+ See Also
+ --------
+ char.join
+
+ """
+ return join(self, seq)
+
+ def ljust(self, width, fillchar=' '):
+ """
+ Return an array with the elements of `self` left-justified in a
+ string of length `width`.
+
+ See Also
+ --------
+ char.ljust
+
+ """
+ return asarray(ljust(self, width, fillchar))
+
+ def lower(self):
+ """
+ Return an array with the elements of `self` converted to
+ lowercase.
+
+ See Also
+ --------
+ char.lower
+
+ """
+ return asarray(lower(self))
+
+ def lstrip(self, chars=None):
+ """
+ For each element in `self`, return a copy with the leading characters
+ removed.
+
+ See Also
+ --------
+ char.lstrip
+
+ """
+ return lstrip(self, chars)
+
+ def partition(self, sep):
+ """
+ Partition each element in `self` around `sep`.
+
+ See Also
+ --------
+ partition
+ """
+ return asarray(partition(self, sep))
+
+ def replace(self, old, new, count=None):
+ """
+ For each element in `self`, return a copy of the string with all
+ occurrences of substring `old` replaced by `new`.
+
+ See Also
+ --------
+ char.replace
+
+ """
+ return replace(self, old, new, count if count is not None else -1)
+
+ def rfind(self, sub, start=0, end=None):
+ """
+ For each element in `self`, return the highest index in the string
+ where substring `sub` is found, such that `sub` is contained
+ within [`start`, `end`].
+
+ See Also
+ --------
+ char.rfind
+
+ """
+ return rfind(self, sub, start, end)
+
+ def rindex(self, sub, start=0, end=None):
+ """
+ Like `rfind`, but raises :exc:`ValueError` when the substring `sub` is
+ not found.
+
+ See Also
+ --------
+ char.rindex
+
+ """
+ return rindex(self, sub, start, end)
+
+ def rjust(self, width, fillchar=' '):
+ """
+ Return an array with the elements of `self`
+ right-justified in a string of length `width`.
+
+ See Also
+ --------
+ char.rjust
+
+ """
+ return asarray(rjust(self, width, fillchar))
+
+ def rpartition(self, sep):
+ """
+ Partition each element in `self` around `sep`.
+
+ See Also
+ --------
+ rpartition
+ """
+ return asarray(rpartition(self, sep))
+
+ def rsplit(self, sep=None, maxsplit=None):
+ """
+ For each element in `self`, return a list of the words in
+ the string, using `sep` as the delimiter string.
+
+ See Also
+ --------
+ char.rsplit
+
+ """
+ return rsplit(self, sep, maxsplit)
+
+ def rstrip(self, chars=None):
+ """
+ For each element in `self`, return a copy with the trailing
+ characters removed.
+
+ See Also
+ --------
+ char.rstrip
+
+ """
+ return rstrip(self, chars)
+
+ def split(self, sep=None, maxsplit=None):
+ """
+ For each element in `self`, return a list of the words in the
+ string, using `sep` as the delimiter string.
+
+ See Also
+ --------
+ char.split
+
+ """
+ return split(self, sep, maxsplit)
+
+ def splitlines(self, keepends=None):
+ """
+ For each element in `self`, return a list of the lines in the
+ element, breaking at line boundaries.
+
+ See Also
+ --------
+ char.splitlines
+
+ """
+ return splitlines(self, keepends)
+
+ def startswith(self, prefix, start=0, end=None):
+ """
+ Returns a boolean array which is `True` where the string element
+ in `self` starts with `prefix`, otherwise `False`.
+
+ See Also
+ --------
+ char.startswith
+
+ """
+ return startswith(self, prefix, start, end)
+
+ def strip(self, chars=None):
+ """
+ For each element in `self`, return a copy with the leading and
+ trailing characters removed.
+
+ See Also
+ --------
+ char.strip
+
+ """
+ return strip(self, chars)
+
+ def swapcase(self):
+ """
+ For each element in `self`, return a copy of the string with
+ uppercase characters converted to lowercase and vice versa.
+
+ See Also
+ --------
+ char.swapcase
+
+ """
+ return asarray(swapcase(self))
+
+ def title(self):
+ """
+ For each element in `self`, return a titlecased version of the
+ string: words start with uppercase characters, all remaining cased
+ characters are lowercase.
+
+ See Also
+ --------
+ char.title
+
+ """
+ return asarray(title(self))
+
+ def translate(self, table, deletechars=None):
+ """
+ For each element in `self`, return a copy of the string where
+ all characters occurring in the optional argument
+ `deletechars` are removed, and the remaining characters have
+ been mapped through the given translation table.
+
+ See Also
+ --------
+ char.translate
+
+ """
+ return asarray(translate(self, table, deletechars))
+
+ def upper(self):
+ """
+ Return an array with the elements of `self` converted to
+ uppercase.
+
+ See Also
+ --------
+ char.upper
+
+ """
+ return asarray(upper(self))
+
+ def zfill(self, width):
+ """
+ Return the numeric string left-filled with zeros in a string of
+ length `width`.
+
+ See Also
+ --------
+ char.zfill
+
+ """
+ return asarray(zfill(self, width))
+
+ def isnumeric(self):
+ """
+ For each element in `self`, return True if there are only
+ numeric characters in the element.
+
+ See Also
+ --------
+ char.isnumeric
+
+ """
+ return isnumeric(self)
+
+ def isdecimal(self):
+ """
+ For each element in `self`, return True if there are only
+ decimal characters in the element.
+
+ See Also
+ --------
+ char.isdecimal
+
+ """
+ return isdecimal(self)
+
+
+@set_module("numpy.char")
+def array(obj, itemsize=None, copy=True, unicode=None, order=None):
+ """
+ Create a `~numpy.char.chararray`.
+
+ .. note::
+ This class is provided for numarray backward-compatibility.
+ New code (not concerned with numarray compatibility) should use
+ arrays of type `bytes_` or `str_` and use the free functions
+ in :mod:`numpy.char` for fast vectorized string operations instead.
+
+ Versus a NumPy array of dtype `bytes_` or `str_`, this
+ class adds the following functionality:
+
+ 1) values automatically have whitespace removed from the end
+ when indexed
+
+ 2) comparison operators automatically remove whitespace from the
+ end when comparing values
+
+ 3) vectorized string operations are provided as methods
+ (e.g. `chararray.endswith `)
+ and infix operators (e.g. ``+, *, %``)
+
+ Parameters
+ ----------
+ obj : array of str or unicode-like
+
+ itemsize : int, optional
+ `itemsize` is the number of characters per scalar in the
+ resulting array. If `itemsize` is None, and `obj` is an
+ object array or a Python list, the `itemsize` will be
+ automatically determined. If `itemsize` is provided and `obj`
+ is of type str or unicode, then the `obj` string will be
+ chunked into `itemsize` pieces.
+
+ copy : bool, optional
+ If true (default), then the object is copied. Otherwise, a copy
+ will only be made if ``__array__`` returns a copy, if obj is a
+ nested sequence, or if a copy is needed to satisfy any of the other
+ requirements (`itemsize`, unicode, `order`, etc.).
+
+ unicode : bool, optional
+ When true, the resulting `~numpy.char.chararray` can contain Unicode
+ characters, when false only 8-bit characters. If unicode is
+ None and `obj` is one of the following:
+
+ - a `~numpy.char.chararray`,
+ - an ndarray of type :class:`str_` or :class:`bytes_`
+ - a Python :class:`str` or :class:`bytes` object,
+
+ then the unicode setting of the output array will be
+ automatically determined.
+
+ order : {'C', 'F', 'A'}, optional
+ Specify the order of the array. If order is 'C' (default), then the
+ array will be in C-contiguous order (last-index varies the
+ fastest). If order is 'F', then the returned array
+ will be in Fortran-contiguous order (first-index varies the
+ fastest). If order is 'A', then the returned array may
+ be in any order (either C-, Fortran-contiguous, or even
+ discontiguous).
+
+ Examples
+ --------
+
+ >>> import numpy as np
+ >>> char_array = np.char.array(['hello', 'world', 'numpy','array'])
+ >>> char_array
+ chararray(['hello', 'world', 'numpy', 'array'], dtype='`)
+ and infix operators (e.g. ``+``, ``*``, ``%``)
+
+ Parameters
+ ----------
+ obj : array of str or unicode-like
+
+ itemsize : int, optional
+ `itemsize` is the number of characters per scalar in the
+ resulting array. If `itemsize` is None, and `obj` is an
+ object array or a Python list, the `itemsize` will be
+ automatically determined. If `itemsize` is provided and `obj`
+ is of type str or unicode, then the `obj` string will be
+ chunked into `itemsize` pieces.
+
+ unicode : bool, optional
+ When true, the resulting `~numpy.char.chararray` can contain Unicode
+ characters, when false only 8-bit characters. If unicode is
+ None and `obj` is one of the following:
+
+ - a `~numpy.char.chararray`,
+ - an ndarray of type `str_` or `unicode_`
+ - a Python str or unicode object,
+
+ then the unicode setting of the output array will be
+ automatically determined.
+
+ order : {'C', 'F'}, optional
+ Specify the order of the array. If order is 'C' (default), then the
+ array will be in C-contiguous order (last-index varies the
+ fastest). If order is 'F', then the returned array
+ will be in Fortran-contiguous order (first-index varies the
+ fastest).
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.char.asarray(['hello', 'world'])
+ chararray(['hello', 'world'], dtype=' chararray[_Shape, dtype[bytes_]]: ...
+ @overload
+ def __new__(
+ subtype,
+ shape: _ShapeLike,
+ itemsize: SupportsIndex | SupportsInt = ...,
+ unicode: L[True] = ...,
+ buffer: _SupportsBuffer = ...,
+ offset: SupportsIndex = ...,
+ strides: _ShapeLike = ...,
+ order: _OrderKACF = ...,
+ ) -> chararray[_Shape, dtype[str_]]: ...
+
+ def __array_finalize__(self, obj: object) -> None: ...
+ def __mul__(self, other: i_co) -> chararray[_Shape, _CharDType_co]: ...
+ def __rmul__(self, other: i_co) -> chararray[_Shape, _CharDType_co]: ...
+ def __mod__(self, i: Any) -> chararray[_Shape, _CharDType_co]: ...
+
+ @overload
+ def __eq__(
+ self: _CharArray[str_],
+ other: U_co,
+ ) -> NDArray[np.bool]: ...
+ @overload
+ def __eq__(
+ self: _CharArray[bytes_],
+ other: S_co,
+ ) -> NDArray[np.bool]: ...
+
+ @overload
+ def __ne__(
+ self: _CharArray[str_],
+ other: U_co,
+ ) -> NDArray[np.bool]: ...
+ @overload
+ def __ne__(
+ self: _CharArray[bytes_],
+ other: S_co,
+ ) -> NDArray[np.bool]: ...
+
+ @overload
+ def __ge__(
+ self: _CharArray[str_],
+ other: U_co,
+ ) -> NDArray[np.bool]: ...
+ @overload
+ def __ge__(
+ self: _CharArray[bytes_],
+ other: S_co,
+ ) -> NDArray[np.bool]: ...
+
+ @overload
+ def __le__(
+ self: _CharArray[str_],
+ other: U_co,
+ ) -> NDArray[np.bool]: ...
+ @overload
+ def __le__(
+ self: _CharArray[bytes_],
+ other: S_co,
+ ) -> NDArray[np.bool]: ...
+
+ @overload
+ def __gt__(
+ self: _CharArray[str_],
+ other: U_co,
+ ) -> NDArray[np.bool]: ...
+ @overload
+ def __gt__(
+ self: _CharArray[bytes_],
+ other: S_co,
+ ) -> NDArray[np.bool]: ...
+
+ @overload
+ def __lt__(
+ self: _CharArray[str_],
+ other: U_co,
+ ) -> NDArray[np.bool]: ...
+ @overload
+ def __lt__(
+ self: _CharArray[bytes_],
+ other: S_co,
+ ) -> NDArray[np.bool]: ...
+
+ @overload
+ def __add__(
+ self: _CharArray[str_],
+ other: U_co,
+ ) -> _CharArray[str_]: ...
+ @overload
+ def __add__(
+ self: _CharArray[bytes_],
+ other: S_co,
+ ) -> _CharArray[bytes_]: ...
+
+ @overload
+ def __radd__(
+ self: _CharArray[str_],
+ other: U_co,
+ ) -> _CharArray[str_]: ...
+ @overload
+ def __radd__(
+ self: _CharArray[bytes_],
+ other: S_co,
+ ) -> _CharArray[bytes_]: ...
+
+ @overload
+ def center(
+ self: _CharArray[str_],
+ width: i_co,
+ fillchar: U_co = ...,
+ ) -> _CharArray[str_]: ...
+ @overload
+ def center(
+ self: _CharArray[bytes_],
+ width: i_co,
+ fillchar: S_co = ...,
+ ) -> _CharArray[bytes_]: ...
+
+ @overload
+ def count(
+ self: _CharArray[str_],
+ sub: U_co,
+ start: i_co = ...,
+ end: None | i_co = ...,
+ ) -> NDArray[int_]: ...
+ @overload
+ def count(
+ self: _CharArray[bytes_],
+ sub: S_co,
+ start: i_co = ...,
+ end: None | i_co = ...,
+ ) -> NDArray[int_]: ...
+
+ def decode(
+ self: _CharArray[bytes_],
+ encoding: None | str = ...,
+ errors: None | str = ...,
+ ) -> _CharArray[str_]: ...
+
+ def encode(
+ self: _CharArray[str_],
+ encoding: None | str = ...,
+ errors: None | str = ...,
+ ) -> _CharArray[bytes_]: ...
+
+ @overload
+ def endswith(
+ self: _CharArray[str_],
+ suffix: U_co,
+ start: i_co = ...,
+ end: None | i_co = ...,
+ ) -> NDArray[np.bool]: ...
+ @overload
+ def endswith(
+ self: _CharArray[bytes_],
+ suffix: S_co,
+ start: i_co = ...,
+ end: None | i_co = ...,
+ ) -> NDArray[np.bool]: ...
+
+ def expandtabs(
+ self,
+ tabsize: i_co = ...,
+ ) -> chararray[_Shape, _CharDType_co]: ...
+
+ @overload
+ def find(
+ self: _CharArray[str_],
+ sub: U_co,
+ start: i_co = ...,
+ end: None | i_co = ...,
+ ) -> NDArray[int_]: ...
+ @overload
+ def find(
+ self: _CharArray[bytes_],
+ sub: S_co,
+ start: i_co = ...,
+ end: None | i_co = ...,
+ ) -> NDArray[int_]: ...
+
+ @overload
+ def index(
+ self: _CharArray[str_],
+ sub: U_co,
+ start: i_co = ...,
+ end: None | i_co = ...,
+ ) -> NDArray[int_]: ...
+ @overload
+ def index(
+ self: _CharArray[bytes_],
+ sub: S_co,
+ start: i_co = ...,
+ end: None | i_co = ...,
+ ) -> NDArray[int_]: ...
+
+ @overload
+ def join(
+ self: _CharArray[str_],
+ seq: U_co,
+ ) -> _CharArray[str_]: ...
+ @overload
+ def join(
+ self: _CharArray[bytes_],
+ seq: S_co,
+ ) -> _CharArray[bytes_]: ...
+
+ @overload
+ def ljust(
+ self: _CharArray[str_],
+ width: i_co,
+ fillchar: U_co = ...,
+ ) -> _CharArray[str_]: ...
+ @overload
+ def ljust(
+ self: _CharArray[bytes_],
+ width: i_co,
+ fillchar: S_co = ...,
+ ) -> _CharArray[bytes_]: ...
+
+ @overload
+ def lstrip(
+ self: _CharArray[str_],
+ chars: None | U_co = ...,
+ ) -> _CharArray[str_]: ...
+ @overload
+ def lstrip(
+ self: _CharArray[bytes_],
+ chars: None | S_co = ...,
+ ) -> _CharArray[bytes_]: ...
+
+ @overload
+ def partition(
+ self: _CharArray[str_],
+ sep: U_co,
+ ) -> _CharArray[str_]: ...
+ @overload
+ def partition(
+ self: _CharArray[bytes_],
+ sep: S_co,
+ ) -> _CharArray[bytes_]: ...
+
+ @overload
+ def replace(
+ self: _CharArray[str_],
+ old: U_co,
+ new: U_co,
+ count: None | i_co = ...,
+ ) -> _CharArray[str_]: ...
+ @overload
+ def replace(
+ self: _CharArray[bytes_],
+ old: S_co,
+ new: S_co,
+ count: None | i_co = ...,
+ ) -> _CharArray[bytes_]: ...
+
+ @overload
+ def rfind(
+ self: _CharArray[str_],
+ sub: U_co,
+ start: i_co = ...,
+ end: None | i_co = ...,
+ ) -> NDArray[int_]: ...
+ @overload
+ def rfind(
+ self: _CharArray[bytes_],
+ sub: S_co,
+ start: i_co = ...,
+ end: None | i_co = ...,
+ ) -> NDArray[int_]: ...
+
+ @overload
+ def rindex(
+ self: _CharArray[str_],
+ sub: U_co,
+ start: i_co = ...,
+ end: None | i_co = ...,
+ ) -> NDArray[int_]: ...
+ @overload
+ def rindex(
+ self: _CharArray[bytes_],
+ sub: S_co,
+ start: i_co = ...,
+ end: None | i_co = ...,
+ ) -> NDArray[int_]: ...
+
+ @overload
+ def rjust(
+ self: _CharArray[str_],
+ width: i_co,
+ fillchar: U_co = ...,
+ ) -> _CharArray[str_]: ...
+ @overload
+ def rjust(
+ self: _CharArray[bytes_],
+ width: i_co,
+ fillchar: S_co = ...,
+ ) -> _CharArray[bytes_]: ...
+
+ @overload
+ def rpartition(
+ self: _CharArray[str_],
+ sep: U_co,
+ ) -> _CharArray[str_]: ...
+ @overload
+ def rpartition(
+ self: _CharArray[bytes_],
+ sep: S_co,
+ ) -> _CharArray[bytes_]: ...
+
+ @overload
+ def rsplit(
+ self: _CharArray[str_],
+ sep: None | U_co = ...,
+ maxsplit: None | i_co = ...,
+ ) -> NDArray[object_]: ...
+ @overload
+ def rsplit(
+ self: _CharArray[bytes_],
+ sep: None | S_co = ...,
+ maxsplit: None | i_co = ...,
+ ) -> NDArray[object_]: ...
+
+ @overload
+ def rstrip(
+ self: _CharArray[str_],
+ chars: None | U_co = ...,
+ ) -> _CharArray[str_]: ...
+ @overload
+ def rstrip(
+ self: _CharArray[bytes_],
+ chars: None | S_co = ...,
+ ) -> _CharArray[bytes_]: ...
+
+ @overload
+ def split(
+ self: _CharArray[str_],
+ sep: None | U_co = ...,
+ maxsplit: None | i_co = ...,
+ ) -> NDArray[object_]: ...
+ @overload
+ def split(
+ self: _CharArray[bytes_],
+ sep: None | S_co = ...,
+ maxsplit: None | i_co = ...,
+ ) -> NDArray[object_]: ...
+
+ def splitlines(self, keepends: None | b_co = ...) -> NDArray[object_]: ...
+
+ @overload
+ def startswith(
+ self: _CharArray[str_],
+ prefix: U_co,
+ start: i_co = ...,
+ end: None | i_co = ...,
+ ) -> NDArray[np.bool]: ...
+ @overload
+ def startswith(
+ self: _CharArray[bytes_],
+ prefix: S_co,
+ start: i_co = ...,
+ end: None | i_co = ...,
+ ) -> NDArray[np.bool]: ...
+
+ @overload
+ def strip(
+ self: _CharArray[str_],
+ chars: None | U_co = ...,
+ ) -> _CharArray[str_]: ...
+ @overload
+ def strip(
+ self: _CharArray[bytes_],
+ chars: None | S_co = ...,
+ ) -> _CharArray[bytes_]: ...
+
+ @overload
+ def translate(
+ self: _CharArray[str_],
+ table: U_co,
+ deletechars: None | U_co = ...,
+ ) -> _CharArray[str_]: ...
+ @overload
+ def translate(
+ self: _CharArray[bytes_],
+ table: S_co,
+ deletechars: None | S_co = ...,
+ ) -> _CharArray[bytes_]: ...
+
+ def zfill(self, width: i_co) -> chararray[_Shape, _CharDType_co]: ...
+ def capitalize(self) -> chararray[_ShapeT_co, _CharDType_co]: ...
+ def title(self) -> chararray[_ShapeT_co, _CharDType_co]: ...
+ def swapcase(self) -> chararray[_ShapeT_co, _CharDType_co]: ...
+ def lower(self) -> chararray[_ShapeT_co, _CharDType_co]: ...
+ def upper(self) -> chararray[_ShapeT_co, _CharDType_co]: ...
+ def isalnum(self) -> ndarray[_ShapeT_co, dtype[np.bool]]: ...
+ def isalpha(self) -> ndarray[_ShapeT_co, dtype[np.bool]]: ...
+ def isdigit(self) -> ndarray[_ShapeT_co, dtype[np.bool]]: ...
+ def islower(self) -> ndarray[_ShapeT_co, dtype[np.bool]]: ...
+ def isspace(self) -> ndarray[_ShapeT_co, dtype[np.bool]]: ...
+ def istitle(self) -> ndarray[_ShapeT_co, dtype[np.bool]]: ...
+ def isupper(self) -> ndarray[_ShapeT_co, dtype[np.bool]]: ...
+ def isnumeric(self) -> ndarray[_ShapeT_co, dtype[np.bool]]: ...
+ def isdecimal(self) -> ndarray[_ShapeT_co, dtype[np.bool]]: ...
+
+
+# Comparison
+@overload
+def equal(x1: U_co, x2: U_co) -> NDArray[np.bool]: ...
+@overload
+def equal(x1: S_co, x2: S_co) -> NDArray[np.bool]: ...
+@overload
+def equal(x1: T_co, x2: T_co) -> NDArray[np.bool]: ...
+
+@overload
+def not_equal(x1: U_co, x2: U_co) -> NDArray[np.bool]: ...
+@overload
+def not_equal(x1: S_co, x2: S_co) -> NDArray[np.bool]: ...
+@overload
+def not_equal(x1: T_co, x2: T_co) -> NDArray[np.bool]: ...
+
+@overload
+def greater_equal(x1: U_co, x2: U_co) -> NDArray[np.bool]: ...
+@overload
+def greater_equal(x1: S_co, x2: S_co) -> NDArray[np.bool]: ...
+@overload
+def greater_equal(x1: T_co, x2: T_co) -> NDArray[np.bool]: ...
+
+@overload
+def less_equal(x1: U_co, x2: U_co) -> NDArray[np.bool]: ...
+@overload
+def less_equal(x1: S_co, x2: S_co) -> NDArray[np.bool]: ...
+@overload
+def less_equal(x1: T_co, x2: T_co) -> NDArray[np.bool]: ...
+
+@overload
+def greater(x1: U_co, x2: U_co) -> NDArray[np.bool]: ...
+@overload
+def greater(x1: S_co, x2: S_co) -> NDArray[np.bool]: ...
+@overload
+def greater(x1: T_co, x2: T_co) -> NDArray[np.bool]: ...
+
+@overload
+def less(x1: U_co, x2: U_co) -> NDArray[np.bool]: ...
+@overload
+def less(x1: S_co, x2: S_co) -> NDArray[np.bool]: ...
+@overload
+def less(x1: T_co, x2: T_co) -> NDArray[np.bool]: ...
+
+@overload
+def add(x1: U_co, x2: U_co) -> NDArray[np.str_]: ...
+@overload
+def add(x1: S_co, x2: S_co) -> NDArray[np.bytes_]: ...
+@overload
+def add(x1: _StringDTypeSupportsArray, x2: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
+@overload
+def add(x1: T_co, T_co) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def multiply(a: U_co, i: i_co) -> NDArray[np.str_]: ...
+@overload
+def multiply(a: S_co, i: i_co) -> NDArray[np.bytes_]: ...
+@overload
+def multiply(a: _StringDTypeSupportsArray, i: i_co) -> _StringDTypeArray: ...
+@overload
+def multiply(a: T_co, i: i_co) -> _StringDTypeOrUnicodeArray: ...
+
+
+@overload
+def mod(a: U_co, value: Any) -> NDArray[np.str_]: ...
+@overload
+def mod(a: S_co, value: Any) -> NDArray[np.bytes_]: ...
+@overload
+def mod(a: _StringDTypeSupportsArray, value: Any) -> _StringDTypeArray: ...
+@overload
+def mod(a: T_co, value: Any) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def capitalize(a: U_co) -> NDArray[str_]: ...
+@overload
+def capitalize(a: S_co) -> NDArray[bytes_]: ...
+@overload
+def capitalize(a: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
+@overload
+def capitalize(a: T_co) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def center(a: U_co, width: i_co, fillchar: U_co = ...) -> NDArray[str_]: ...
+@overload
+def center(a: S_co, width: i_co, fillchar: S_co = ...) -> NDArray[bytes_]: ...
+@overload
+def center(a: _StringDTypeSupportsArray, width: i_co, fillchar: _StringDTypeSupportsArray = ...) -> _StringDTypeArray: ...
+@overload
+def center(a: T_co, width: i_co, fillchar: T_co = ...) -> _StringDTypeOrUnicodeArray: ...
+
+def decode(
+ a: S_co,
+ encoding: None | str = ...,
+ errors: None | str = ...,
+) -> NDArray[str_]: ...
+def encode(
+ a: U_co | T_co,
+ encoding: None | str = ...,
+ errors: None | str = ...,
+) -> NDArray[bytes_]: ...
+
+@overload
+def expandtabs(a: U_co, tabsize: i_co = ...) -> NDArray[str_]: ...
+@overload
+def expandtabs(a: S_co, tabsize: i_co = ...) -> NDArray[bytes_]: ...
+@overload
+def expandtabs(a: _StringDTypeSupportsArray, tabsize: i_co = ...) -> _StringDTypeArray: ...
+@overload
+def expandtabs(a: T_co, tabsize: i_co = ...) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def join(sep: U_co, seq: U_co) -> NDArray[str_]: ...
+@overload
+def join(sep: S_co, seq: S_co) -> NDArray[bytes_]: ...
+@overload
+def join(sep: _StringDTypeSupportsArray, seq: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
+@overload
+def join(sep: T_co, seq: T_co) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def ljust(a: U_co, width: i_co, fillchar: U_co = ...) -> NDArray[str_]: ...
+@overload
+def ljust(a: S_co, width: i_co, fillchar: S_co = ...) -> NDArray[bytes_]: ...
+@overload
+def ljust(a: _StringDTypeSupportsArray, width: i_co, fillchar: _StringDTypeSupportsArray = ...) -> _StringDTypeArray: ...
+@overload
+def ljust(a: T_co, width: i_co, fillchar: T_co = ...) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def lower(a: U_co) -> NDArray[str_]: ...
+@overload
+def lower(a: S_co) -> NDArray[bytes_]: ...
+@overload
+def lower(a: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
+@overload
+def lower(a: T_co) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def lstrip(a: U_co, chars: None | U_co = ...) -> NDArray[str_]: ...
+@overload
+def lstrip(a: S_co, chars: None | S_co = ...) -> NDArray[bytes_]: ...
+@overload
+def lstrip(a: _StringDTypeSupportsArray, chars: None | _StringDTypeSupportsArray = ...) -> _StringDTypeArray: ...
+@overload
+def lstrip(a: T_co, chars: None | T_co = ...) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def partition(a: U_co, sep: U_co) -> NDArray[str_]: ...
+@overload
+def partition(a: S_co, sep: S_co) -> NDArray[bytes_]: ...
+@overload
+def partition(a: _StringDTypeSupportsArray, sep: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
+@overload
+def partition(a: T_co, sep: T_co) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def replace(
+ a: U_co,
+ old: U_co,
+ new: U_co,
+ count: None | i_co = ...,
+) -> NDArray[str_]: ...
+@overload
+def replace(
+ a: S_co,
+ old: S_co,
+ new: S_co,
+ count: None | i_co = ...,
+) -> NDArray[bytes_]: ...
+@overload
+def replace(
+ a: _StringDTypeSupportsArray,
+ old: _StringDTypeSupportsArray,
+ new: _StringDTypeSupportsArray,
+ count: i_co = ...,
+) -> _StringDTypeArray: ...
+@overload
+def replace(
+ a: T_co,
+ old: T_co,
+ new: T_co,
+ count: i_co = ...,
+) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def rjust(
+ a: U_co,
+ width: i_co,
+ fillchar: U_co = ...,
+) -> NDArray[str_]: ...
+@overload
+def rjust(
+ a: S_co,
+ width: i_co,
+ fillchar: S_co = ...,
+) -> NDArray[bytes_]: ...
+@overload
+def rjust(
+ a: _StringDTypeSupportsArray,
+ width: i_co,
+ fillchar: _StringDTypeSupportsArray = ...,
+) -> _StringDTypeArray: ...
+@overload
+def rjust(
+ a: T_co,
+ width: i_co,
+ fillchar: T_co = ...,
+) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def rpartition(a: U_co, sep: U_co) -> NDArray[str_]: ...
+@overload
+def rpartition(a: S_co, sep: S_co) -> NDArray[bytes_]: ...
+@overload
+def rpartition(a: _StringDTypeSupportsArray, sep: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
+@overload
+def rpartition(a: T_co, sep: T_co) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def rsplit(
+ a: U_co,
+ sep: None | U_co = ...,
+ maxsplit: None | i_co = ...,
+) -> NDArray[object_]: ...
+@overload
+def rsplit(
+ a: S_co,
+ sep: None | S_co = ...,
+ maxsplit: None | i_co = ...,
+) -> NDArray[object_]: ...
+@overload
+def rsplit(
+ a: _StringDTypeSupportsArray,
+ sep: None | _StringDTypeSupportsArray = ...,
+ maxsplit: None | i_co = ...,
+) -> NDArray[object_]: ...
+@overload
+def rsplit(
+ a: T_co,
+ sep: None | T_co = ...,
+ maxsplit: None | i_co = ...,
+) -> NDArray[object_]: ...
+
+@overload
+def rstrip(a: U_co, chars: None | U_co = ...) -> NDArray[str_]: ...
+@overload
+def rstrip(a: S_co, chars: None | S_co = ...) -> NDArray[bytes_]: ...
+@overload
+def rstrip(a: _StringDTypeSupportsArray, chars: None | _StringDTypeSupportsArray = ...) -> _StringDTypeArray: ...
+@overload
+def rstrip(a: T_co, chars: None | T_co = ...) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def split(
+ a: U_co,
+ sep: None | U_co = ...,
+ maxsplit: None | i_co = ...,
+) -> NDArray[object_]: ...
+@overload
+def split(
+ a: S_co,
+ sep: None | S_co = ...,
+ maxsplit: None | i_co = ...,
+) -> NDArray[object_]: ...
+@overload
+def split(
+ a: _StringDTypeSupportsArray,
+ sep: None | _StringDTypeSupportsArray = ...,
+ maxsplit: None | i_co = ...,
+) -> NDArray[object_]: ...
+@overload
+def split(
+ a: T_co,
+ sep: None | T_co = ...,
+ maxsplit: None | i_co = ...,
+) -> NDArray[object_]: ...
+
+def splitlines(a: UST_co, keepends: None | b_co = ...) -> NDArray[np.object_]: ...
+
+@overload
+def strip(a: U_co, chars: None | U_co = ...) -> NDArray[str_]: ...
+@overload
+def strip(a: S_co, chars: None | S_co = ...) -> NDArray[bytes_]: ...
+@overload
+def strip(a: _StringDTypeSupportsArray, chars: None | _StringDTypeSupportsArray = ...) -> _StringDTypeArray: ...
+@overload
+def strip(a: T_co, chars: None | T_co = ...) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def swapcase(a: U_co) -> NDArray[str_]: ...
+@overload
+def swapcase(a: S_co) -> NDArray[bytes_]: ...
+@overload
+def swapcase(a: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
+@overload
+def swapcase(a: T_co) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def title(a: U_co) -> NDArray[str_]: ...
+@overload
+def title(a: S_co) -> NDArray[bytes_]: ...
+@overload
+def title(a: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
+@overload
+def title(a: T_co) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def translate(
+ a: U_co,
+ table: str,
+ deletechars: None | str = ...,
+) -> NDArray[str_]: ...
+@overload
+def translate(
+ a: S_co,
+ table: str,
+ deletechars: None | str = ...,
+) -> NDArray[bytes_]: ...
+@overload
+def translate(
+ a: _StringDTypeSupportsArray,
+ table: str,
+ deletechars: None | str = ...,
+) -> _StringDTypeArray: ...
+@overload
+def translate(
+ a: T_co,
+ table: str,
+ deletechars: None | str = ...,
+) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def upper(a: U_co) -> NDArray[str_]: ...
+@overload
+def upper(a: S_co) -> NDArray[bytes_]: ...
+@overload
+def upper(a: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
+@overload
+def upper(a: T_co) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def zfill(a: U_co, width: i_co) -> NDArray[str_]: ...
+@overload
+def zfill(a: S_co, width: i_co) -> NDArray[bytes_]: ...
+@overload
+def zfill(a: _StringDTypeSupportsArray, width: i_co) -> _StringDTypeArray: ...
+@overload
+def zfill(a: T_co, width: i_co) -> _StringDTypeOrUnicodeArray: ...
+
+# String information
+@overload
+def count(
+ a: U_co,
+ sub: U_co,
+ start: i_co = ...,
+ end: None | i_co = ...,
+) -> NDArray[int_]: ...
+@overload
+def count(
+ a: S_co,
+ sub: S_co,
+ start: i_co = ...,
+ end: None | i_co = ...,
+) -> NDArray[int_]: ...
+@overload
+def count(
+ a: T_co,
+ sub: T_co,
+ start: i_co = ...,
+ end: i_co | None = ...,
+) -> NDArray[np.int_]: ...
+
+@overload
+def endswith(
+ a: U_co,
+ suffix: U_co,
+ start: i_co = ...,
+ end: None | i_co = ...,
+) -> NDArray[np.bool]: ...
+@overload
+def endswith(
+ a: S_co,
+ suffix: S_co,
+ start: i_co = ...,
+ end: None | i_co = ...,
+) -> NDArray[np.bool]: ...
+@overload
+def endswith(
+ a: T_co,
+ suffix: T_co,
+ start: i_co = ...,
+ end: i_co | None = ...,
+) -> NDArray[np.bool]: ...
+
+@overload
+def find(
+ a: U_co,
+ sub: U_co,
+ start: i_co = ...,
+ end: None | i_co = ...,
+) -> NDArray[int_]: ...
+@overload
+def find(
+ a: S_co,
+ sub: S_co,
+ start: i_co = ...,
+ end: None | i_co = ...,
+) -> NDArray[int_]: ...
+@overload
+def find(
+ a: T_co,
+ sub: T_co,
+ start: i_co = ...,
+ end: i_co | None = ...,
+) -> NDArray[np.int_]: ...
+
+@overload
+def index(
+ a: U_co,
+ sub: U_co,
+ start: i_co = ...,
+ end: None | i_co = ...,
+) -> NDArray[int_]: ...
+@overload
+def index(
+ a: S_co,
+ sub: S_co,
+ start: i_co = ...,
+ end: None | i_co = ...,
+) -> NDArray[int_]: ...
+@overload
+def index(
+ a: T_co,
+ sub: T_co,
+ start: i_co = ...,
+ end: i_co | None = ...,
+) -> NDArray[np.int_]: ...
+
+def isalpha(a: UST_co) -> NDArray[np.bool]: ...
+def isalnum(a: UST_co) -> NDArray[np.bool]: ...
+def isdecimal(a: U_co | T_co) -> NDArray[np.bool]: ...
+def isdigit(a: UST_co) -> NDArray[np.bool]: ...
+def islower(a: UST_co) -> NDArray[np.bool]: ...
+def isnumeric(a: U_co | T_co) -> NDArray[np.bool]: ...
+def isspace(a: UST_co) -> NDArray[np.bool]: ...
+def istitle(a: UST_co) -> NDArray[np.bool]: ...
+def isupper(a: UST_co) -> NDArray[np.bool]: ...
+
+@overload
+def rfind(
+ a: U_co,
+ sub: U_co,
+ start: i_co = ...,
+ end: None | i_co = ...,
+) -> NDArray[int_]: ...
+@overload
+def rfind(
+ a: S_co,
+ sub: S_co,
+ start: i_co = ...,
+ end: None | i_co = ...,
+) -> NDArray[int_]: ...
+@overload
+def rfind(
+ a: T_co,
+ sub: T_co,
+ start: i_co = ...,
+ end: i_co | None = ...,
+) -> NDArray[np.int_]: ...
+
+@overload
+def rindex(
+ a: U_co,
+ sub: U_co,
+ start: i_co = ...,
+ end: None | i_co = ...,
+) -> NDArray[int_]: ...
+@overload
+def rindex(
+ a: S_co,
+ sub: S_co,
+ start: i_co = ...,
+ end: None | i_co = ...,
+) -> NDArray[int_]: ...
+@overload
+def rindex(
+ a: T_co,
+ sub: T_co,
+ start: i_co = ...,
+ end: i_co | None = ...,
+) -> NDArray[np.int_]: ...
+
+@overload
+def startswith(
+ a: U_co,
+ prefix: U_co,
+ start: i_co = ...,
+ end: None | i_co = ...,
+) -> NDArray[np.bool]: ...
+@overload
+def startswith(
+ a: S_co,
+ prefix: S_co,
+ start: i_co = ...,
+ end: None | i_co = ...,
+) -> NDArray[np.bool]: ...
+@overload
+def startswith(
+ a: T_co,
+ suffix: T_co,
+ start: i_co = ...,
+ end: i_co | None = ...,
+) -> NDArray[np.bool]: ...
+
+def str_len(A: UST_co) -> NDArray[int_]: ...
+
+# Overload 1 and 2: str- or bytes-based array-likes
+# overload 3: arbitrary object with unicode=False (-> bytes_)
+# overload 4: arbitrary object with unicode=True (-> str_)
+@overload
+def array(
+ obj: U_co,
+ itemsize: None | int = ...,
+ copy: bool = ...,
+ unicode: L[False] = ...,
+ order: _OrderKACF = ...,
+) -> _CharArray[str_]: ...
+@overload
+def array(
+ obj: S_co,
+ itemsize: None | int = ...,
+ copy: bool = ...,
+ unicode: L[False] = ...,
+ order: _OrderKACF = ...,
+) -> _CharArray[bytes_]: ...
+@overload
+def array(
+ obj: object,
+ itemsize: None | int = ...,
+ copy: bool = ...,
+ unicode: L[False] = ...,
+ order: _OrderKACF = ...,
+) -> _CharArray[bytes_]: ...
+@overload
+def array(
+ obj: object,
+ itemsize: None | int = ...,
+ copy: bool = ...,
+ unicode: L[True] = ...,
+ order: _OrderKACF = ...,
+) -> _CharArray[str_]: ...
+
+@overload
+def asarray(
+ obj: U_co,
+ itemsize: None | int = ...,
+ unicode: L[False] = ...,
+ order: _OrderKACF = ...,
+) -> _CharArray[str_]: ...
+@overload
+def asarray(
+ obj: S_co,
+ itemsize: None | int = ...,
+ unicode: L[False] = ...,
+ order: _OrderKACF = ...,
+) -> _CharArray[bytes_]: ...
+@overload
+def asarray(
+ obj: object,
+ itemsize: None | int = ...,
+ unicode: L[False] = ...,
+ order: _OrderKACF = ...,
+) -> _CharArray[bytes_]: ...
+@overload
+def asarray(
+ obj: object,
+ itemsize: None | int = ...,
+ unicode: L[True] = ...,
+ order: _OrderKACF = ...,
+) -> _CharArray[str_]: ...
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/einsumfunc.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/einsumfunc.py
new file mode 100644
index 0000000000000000000000000000000000000000..f74dd46e17825a75d6646a675ce980a1fb80025c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/einsumfunc.py
@@ -0,0 +1,1499 @@
+"""
+Implementation of optimized einsum.
+
+"""
+import itertools
+import operator
+
+from numpy._core.multiarray import c_einsum
+from numpy._core.numeric import asanyarray, tensordot
+from numpy._core.overrides import array_function_dispatch
+
+__all__ = ['einsum', 'einsum_path']
+
+# importing string for string.ascii_letters would be too slow
+# the first import before caching has been measured to take 800 µs (#23777)
+einsum_symbols = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
+einsum_symbols_set = set(einsum_symbols)
+
+
+def _flop_count(idx_contraction, inner, num_terms, size_dictionary):
+ """
+ Computes the number of FLOPS in the contraction.
+
+ Parameters
+ ----------
+ idx_contraction : iterable
+ The indices involved in the contraction
+ inner : bool
+ Does this contraction require an inner product?
+ num_terms : int
+ The number of terms in a contraction
+ size_dictionary : dict
+ The size of each of the indices in idx_contraction
+
+ Returns
+ -------
+ flop_count : int
+ The total number of FLOPS required for the contraction.
+
+ Examples
+ --------
+
+ >>> _flop_count('abc', False, 1, {'a': 2, 'b':3, 'c':5})
+ 30
+
+ >>> _flop_count('abc', True, 2, {'a': 2, 'b':3, 'c':5})
+ 60
+
+ """
+
+ overall_size = _compute_size_by_dict(idx_contraction, size_dictionary)
+ op_factor = max(1, num_terms - 1)
+ if inner:
+ op_factor += 1
+
+ return overall_size * op_factor
+
+def _compute_size_by_dict(indices, idx_dict):
+ """
+ Computes the product of the elements in indices based on the dictionary
+ idx_dict.
+
+ Parameters
+ ----------
+ indices : iterable
+ Indices to base the product on.
+ idx_dict : dictionary
+ Dictionary of index sizes
+
+ Returns
+ -------
+ ret : int
+ The resulting product.
+
+ Examples
+ --------
+ >>> _compute_size_by_dict('abbc', {'a': 2, 'b':3, 'c':5})
+ 90
+
+ """
+ ret = 1
+ for i in indices:
+ ret *= idx_dict[i]
+ return ret
+
+
+def _find_contraction(positions, input_sets, output_set):
+ """
+ Finds the contraction for a given set of input and output sets.
+
+ Parameters
+ ----------
+ positions : iterable
+ Integer positions of terms used in the contraction.
+ input_sets : list
+ List of sets that represent the lhs side of the einsum subscript
+ output_set : set
+ Set that represents the rhs side of the overall einsum subscript
+
+ Returns
+ -------
+ new_result : set
+ The indices of the resulting contraction
+ remaining : list
+ List of sets that have not been contracted, the new set is appended to
+ the end of this list
+ idx_removed : set
+ Indices removed from the entire contraction
+ idx_contraction : set
+ The indices used in the current contraction
+
+ Examples
+ --------
+
+ # A simple dot product test case
+ >>> pos = (0, 1)
+ >>> isets = [set('ab'), set('bc')]
+ >>> oset = set('ac')
+ >>> _find_contraction(pos, isets, oset)
+ ({'a', 'c'}, [{'a', 'c'}], {'b'}, {'a', 'b', 'c'})
+
+ # A more complex case with additional terms in the contraction
+ >>> pos = (0, 2)
+ >>> isets = [set('abd'), set('ac'), set('bdc')]
+ >>> oset = set('ac')
+ >>> _find_contraction(pos, isets, oset)
+ ({'a', 'c'}, [{'a', 'c'}, {'a', 'c'}], {'b', 'd'}, {'a', 'b', 'c', 'd'})
+ """
+
+ idx_contract = set()
+ idx_remain = output_set.copy()
+ remaining = []
+ for ind, value in enumerate(input_sets):
+ if ind in positions:
+ idx_contract |= value
+ else:
+ remaining.append(value)
+ idx_remain |= value
+
+ new_result = idx_remain & idx_contract
+ idx_removed = (idx_contract - new_result)
+ remaining.append(new_result)
+
+ return (new_result, remaining, idx_removed, idx_contract)
+
+
+def _optimal_path(input_sets, output_set, idx_dict, memory_limit):
+ """
+ Computes all possible pair contractions, sieves the results based
+ on ``memory_limit`` and returns the lowest cost path. This algorithm
+ scales factorial with respect to the elements in the list ``input_sets``.
+
+ Parameters
+ ----------
+ input_sets : list
+ List of sets that represent the lhs side of the einsum subscript
+ output_set : set
+ Set that represents the rhs side of the overall einsum subscript
+ idx_dict : dictionary
+ Dictionary of index sizes
+ memory_limit : int
+ The maximum number of elements in a temporary array
+
+ Returns
+ -------
+ path : list
+ The optimal contraction order within the memory limit constraint.
+
+ Examples
+ --------
+ >>> isets = [set('abd'), set('ac'), set('bdc')]
+ >>> oset = set()
+ >>> idx_sizes = {'a': 1, 'b':2, 'c':3, 'd':4}
+ >>> _optimal_path(isets, oset, idx_sizes, 5000)
+ [(0, 2), (0, 1)]
+ """
+
+ full_results = [(0, [], input_sets)]
+ for iteration in range(len(input_sets) - 1):
+ iter_results = []
+
+ # Compute all unique pairs
+ for curr in full_results:
+ cost, positions, remaining = curr
+ for con in itertools.combinations(
+ range(len(input_sets) - iteration), 2
+ ):
+
+ # Find the contraction
+ cont = _find_contraction(con, remaining, output_set)
+ new_result, new_input_sets, idx_removed, idx_contract = cont
+
+ # Sieve the results based on memory_limit
+ new_size = _compute_size_by_dict(new_result, idx_dict)
+ if new_size > memory_limit:
+ continue
+
+ # Build (total_cost, positions, indices_remaining)
+ total_cost = cost + _flop_count(
+ idx_contract, idx_removed, len(con), idx_dict
+ )
+ new_pos = positions + [con]
+ iter_results.append((total_cost, new_pos, new_input_sets))
+
+ # Update combinatorial list, if we did not find anything return best
+ # path + remaining contractions
+ if iter_results:
+ full_results = iter_results
+ else:
+ path = min(full_results, key=lambda x: x[0])[1]
+ path += [tuple(range(len(input_sets) - iteration))]
+ return path
+
+ # If we have not found anything return single einsum contraction
+ if len(full_results) == 0:
+ return [tuple(range(len(input_sets)))]
+
+ path = min(full_results, key=lambda x: x[0])[1]
+ return path
+
+def _parse_possible_contraction(
+ positions, input_sets, output_set, idx_dict,
+ memory_limit, path_cost, naive_cost
+ ):
+ """Compute the cost (removed size + flops) and resultant indices for
+ performing the contraction specified by ``positions``.
+
+ Parameters
+ ----------
+ positions : tuple of int
+ The locations of the proposed tensors to contract.
+ input_sets : list of sets
+ The indices found on each tensors.
+ output_set : set
+ The output indices of the expression.
+ idx_dict : dict
+ Mapping of each index to its size.
+ memory_limit : int
+ The total allowed size for an intermediary tensor.
+ path_cost : int
+ The contraction cost so far.
+ naive_cost : int
+ The cost of the unoptimized expression.
+
+ Returns
+ -------
+ cost : (int, int)
+ A tuple containing the size of any indices removed, and the flop cost.
+ positions : tuple of int
+ The locations of the proposed tensors to contract.
+ new_input_sets : list of sets
+ The resulting new list of indices if this proposed contraction
+ is performed.
+
+ """
+
+ # Find the contraction
+ contract = _find_contraction(positions, input_sets, output_set)
+ idx_result, new_input_sets, idx_removed, idx_contract = contract
+
+ # Sieve the results based on memory_limit
+ new_size = _compute_size_by_dict(idx_result, idx_dict)
+ if new_size > memory_limit:
+ return None
+
+ # Build sort tuple
+ old_sizes = (
+ _compute_size_by_dict(input_sets[p], idx_dict) for p in positions
+ )
+ removed_size = sum(old_sizes) - new_size
+
+ # NB: removed_size used to be just the size of any removed indices i.e.:
+ # helpers.compute_size_by_dict(idx_removed, idx_dict)
+ cost = _flop_count(idx_contract, idx_removed, len(positions), idx_dict)
+ sort = (-removed_size, cost)
+
+ # Sieve based on total cost as well
+ if (path_cost + cost) > naive_cost:
+ return None
+
+ # Add contraction to possible choices
+ return [sort, positions, new_input_sets]
+
+
+def _update_other_results(results, best):
+ """Update the positions and provisional input_sets of ``results``
+ based on performing the contraction result ``best``. Remove any
+ involving the tensors contracted.
+
+ Parameters
+ ----------
+ results : list
+ List of contraction results produced by
+ ``_parse_possible_contraction``.
+ best : list
+ The best contraction of ``results`` i.e. the one that
+ will be performed.
+
+ Returns
+ -------
+ mod_results : list
+ The list of modified results, updated with outcome of
+ ``best`` contraction.
+ """
+
+ best_con = best[1]
+ bx, by = best_con
+ mod_results = []
+
+ for cost, (x, y), con_sets in results:
+
+ # Ignore results involving tensors just contracted
+ if x in best_con or y in best_con:
+ continue
+
+ # Update the input_sets
+ del con_sets[by - int(by > x) - int(by > y)]
+ del con_sets[bx - int(bx > x) - int(bx > y)]
+ con_sets.insert(-1, best[2][-1])
+
+ # Update the position indices
+ mod_con = x - int(x > bx) - int(x > by), y - int(y > bx) - int(y > by)
+ mod_results.append((cost, mod_con, con_sets))
+
+ return mod_results
+
+def _greedy_path(input_sets, output_set, idx_dict, memory_limit):
+ """
+ Finds the path by contracting the best pair until the input list is
+ exhausted. The best pair is found by minimizing the tuple
+ ``(-prod(indices_removed), cost)``. What this amounts to is prioritizing
+ matrix multiplication or inner product operations, then Hadamard like
+ operations, and finally outer operations. Outer products are limited by
+ ``memory_limit``. This algorithm scales cubically with respect to the
+ number of elements in the list ``input_sets``.
+
+ Parameters
+ ----------
+ input_sets : list
+ List of sets that represent the lhs side of the einsum subscript
+ output_set : set
+ Set that represents the rhs side of the overall einsum subscript
+ idx_dict : dictionary
+ Dictionary of index sizes
+ memory_limit : int
+ The maximum number of elements in a temporary array
+
+ Returns
+ -------
+ path : list
+ The greedy contraction order within the memory limit constraint.
+
+ Examples
+ --------
+ >>> isets = [set('abd'), set('ac'), set('bdc')]
+ >>> oset = set()
+ >>> idx_sizes = {'a': 1, 'b':2, 'c':3, 'd':4}
+ >>> _greedy_path(isets, oset, idx_sizes, 5000)
+ [(0, 2), (0, 1)]
+ """
+
+ # Handle trivial cases that leaked through
+ if len(input_sets) == 1:
+ return [(0,)]
+ elif len(input_sets) == 2:
+ return [(0, 1)]
+
+ # Build up a naive cost
+ contract = _find_contraction(
+ range(len(input_sets)), input_sets, output_set
+ )
+ idx_result, new_input_sets, idx_removed, idx_contract = contract
+ naive_cost = _flop_count(
+ idx_contract, idx_removed, len(input_sets), idx_dict
+ )
+
+ # Initially iterate over all pairs
+ comb_iter = itertools.combinations(range(len(input_sets)), 2)
+ known_contractions = []
+
+ path_cost = 0
+ path = []
+
+ for iteration in range(len(input_sets) - 1):
+
+ # Iterate over all pairs on the first step, only previously
+ # found pairs on subsequent steps
+ for positions in comb_iter:
+
+ # Always initially ignore outer products
+ if input_sets[positions[0]].isdisjoint(input_sets[positions[1]]):
+ continue
+
+ result = _parse_possible_contraction(
+ positions, input_sets, output_set, idx_dict,
+ memory_limit, path_cost, naive_cost
+ )
+ if result is not None:
+ known_contractions.append(result)
+
+ # If we do not have a inner contraction, rescan pairs
+ # including outer products
+ if len(known_contractions) == 0:
+
+ # Then check the outer products
+ for positions in itertools.combinations(
+ range(len(input_sets)), 2
+ ):
+ result = _parse_possible_contraction(
+ positions, input_sets, output_set, idx_dict,
+ memory_limit, path_cost, naive_cost
+ )
+ if result is not None:
+ known_contractions.append(result)
+
+ # If we still did not find any remaining contractions,
+ # default back to einsum like behavior
+ if len(known_contractions) == 0:
+ path.append(tuple(range(len(input_sets))))
+ break
+
+ # Sort based on first index
+ best = min(known_contractions, key=lambda x: x[0])
+
+ # Now propagate as many unused contractions as possible
+ # to the next iteration
+ known_contractions = _update_other_results(known_contractions, best)
+
+ # Next iteration only compute contractions with the new tensor
+ # All other contractions have been accounted for
+ input_sets = best[2]
+ new_tensor_pos = len(input_sets) - 1
+ comb_iter = ((i, new_tensor_pos) for i in range(new_tensor_pos))
+
+ # Update path and total cost
+ path.append(best[1])
+ path_cost += best[0][1]
+
+ return path
+
+
+def _can_dot(inputs, result, idx_removed):
+ """
+ Checks if we can use BLAS (np.tensordot) call and its beneficial to do so.
+
+ Parameters
+ ----------
+ inputs : list of str
+ Specifies the subscripts for summation.
+ result : str
+ Resulting summation.
+ idx_removed : set
+ Indices that are removed in the summation
+
+
+ Returns
+ -------
+ type : bool
+ Returns true if BLAS should and can be used, else False
+
+ Notes
+ -----
+ If the operations is BLAS level 1 or 2 and is not already aligned
+ we default back to einsum as the memory movement to copy is more
+ costly than the operation itself.
+
+
+ Examples
+ --------
+
+ # Standard GEMM operation
+ >>> _can_dot(['ij', 'jk'], 'ik', set('j'))
+ True
+
+ # Can use the standard BLAS, but requires odd data movement
+ >>> _can_dot(['ijj', 'jk'], 'ik', set('j'))
+ False
+
+ # DDOT where the memory is not aligned
+ >>> _can_dot(['ijk', 'ikj'], '', set('ijk'))
+ False
+
+ """
+
+ # All `dot` calls remove indices
+ if len(idx_removed) == 0:
+ return False
+
+ # BLAS can only handle two operands
+ if len(inputs) != 2:
+ return False
+
+ input_left, input_right = inputs
+
+ for c in set(input_left + input_right):
+ # can't deal with repeated indices on same input or more than 2 total
+ nl, nr = input_left.count(c), input_right.count(c)
+ if (nl > 1) or (nr > 1) or (nl + nr > 2):
+ return False
+
+ # can't do implicit summation or dimension collapse e.g.
+ # "ab,bc->c" (implicitly sum over 'a')
+ # "ab,ca->ca" (take diagonal of 'a')
+ if nl + nr - 1 == int(c in result):
+ return False
+
+ # Build a few temporaries
+ set_left = set(input_left)
+ set_right = set(input_right)
+ keep_left = set_left - idx_removed
+ keep_right = set_right - idx_removed
+ rs = len(idx_removed)
+
+ # At this point we are a DOT, GEMV, or GEMM operation
+
+ # Handle inner products
+
+ # DDOT with aligned data
+ if input_left == input_right:
+ return True
+
+ # DDOT without aligned data (better to use einsum)
+ if set_left == set_right:
+ return False
+
+ # Handle the 4 possible (aligned) GEMV or GEMM cases
+
+ # GEMM or GEMV no transpose
+ if input_left[-rs:] == input_right[:rs]:
+ return True
+
+ # GEMM or GEMV transpose both
+ if input_left[:rs] == input_right[-rs:]:
+ return True
+
+ # GEMM or GEMV transpose right
+ if input_left[-rs:] == input_right[-rs:]:
+ return True
+
+ # GEMM or GEMV transpose left
+ if input_left[:rs] == input_right[:rs]:
+ return True
+
+ # Einsum is faster than GEMV if we have to copy data
+ if not keep_left or not keep_right:
+ return False
+
+ # We are a matrix-matrix product, but we need to copy data
+ return True
+
+
+def _parse_einsum_input(operands):
+ """
+ A reproduction of einsum c side einsum parsing in python.
+
+ Returns
+ -------
+ input_strings : str
+ Parsed input strings
+ output_string : str
+ Parsed output string
+ operands : list of array_like
+ The operands to use in the numpy contraction
+
+ Examples
+ --------
+ The operand list is simplified to reduce printing:
+
+ >>> np.random.seed(123)
+ >>> a = np.random.rand(4, 4)
+ >>> b = np.random.rand(4, 4, 4)
+ >>> _parse_einsum_input(('...a,...a->...', a, b))
+ ('za,xza', 'xz', [a, b]) # may vary
+
+ >>> _parse_einsum_input((a, [Ellipsis, 0], b, [Ellipsis, 0]))
+ ('za,xza', 'xz', [a, b]) # may vary
+ """
+
+ if len(operands) == 0:
+ raise ValueError("No input operands")
+
+ if isinstance(operands[0], str):
+ subscripts = operands[0].replace(" ", "")
+ operands = [asanyarray(v) for v in operands[1:]]
+
+ # Ensure all characters are valid
+ for s in subscripts:
+ if s in '.,->':
+ continue
+ if s not in einsum_symbols:
+ raise ValueError("Character %s is not a valid symbol." % s)
+
+ else:
+ tmp_operands = list(operands)
+ operand_list = []
+ subscript_list = []
+ for p in range(len(operands) // 2):
+ operand_list.append(tmp_operands.pop(0))
+ subscript_list.append(tmp_operands.pop(0))
+
+ output_list = tmp_operands[-1] if len(tmp_operands) else None
+ operands = [asanyarray(v) for v in operand_list]
+ subscripts = ""
+ last = len(subscript_list) - 1
+ for num, sub in enumerate(subscript_list):
+ for s in sub:
+ if s is Ellipsis:
+ subscripts += "..."
+ else:
+ try:
+ s = operator.index(s)
+ except TypeError as e:
+ raise TypeError(
+ "For this input type lists must contain "
+ "either int or Ellipsis"
+ ) from e
+ subscripts += einsum_symbols[s]
+ if num != last:
+ subscripts += ","
+
+ if output_list is not None:
+ subscripts += "->"
+ for s in output_list:
+ if s is Ellipsis:
+ subscripts += "..."
+ else:
+ try:
+ s = operator.index(s)
+ except TypeError as e:
+ raise TypeError(
+ "For this input type lists must contain "
+ "either int or Ellipsis"
+ ) from e
+ subscripts += einsum_symbols[s]
+ # Check for proper "->"
+ if ("-" in subscripts) or (">" in subscripts):
+ invalid = (subscripts.count("-") > 1) or (subscripts.count(">") > 1)
+ if invalid or (subscripts.count("->") != 1):
+ raise ValueError("Subscripts can only contain one '->'.")
+
+ # Parse ellipses
+ if "." in subscripts:
+ used = subscripts.replace(".", "").replace(",", "").replace("->", "")
+ unused = list(einsum_symbols_set - set(used))
+ ellipse_inds = "".join(unused)
+ longest = 0
+
+ if "->" in subscripts:
+ input_tmp, output_sub = subscripts.split("->")
+ split_subscripts = input_tmp.split(",")
+ out_sub = True
+ else:
+ split_subscripts = subscripts.split(',')
+ out_sub = False
+
+ for num, sub in enumerate(split_subscripts):
+ if "." in sub:
+ if (sub.count(".") != 3) or (sub.count("...") != 1):
+ raise ValueError("Invalid Ellipses.")
+
+ # Take into account numerical values
+ if operands[num].shape == ():
+ ellipse_count = 0
+ else:
+ ellipse_count = max(operands[num].ndim, 1)
+ ellipse_count -= (len(sub) - 3)
+
+ if ellipse_count > longest:
+ longest = ellipse_count
+
+ if ellipse_count < 0:
+ raise ValueError("Ellipses lengths do not match.")
+ elif ellipse_count == 0:
+ split_subscripts[num] = sub.replace('...', '')
+ else:
+ rep_inds = ellipse_inds[-ellipse_count:]
+ split_subscripts[num] = sub.replace('...', rep_inds)
+
+ subscripts = ",".join(split_subscripts)
+ if longest == 0:
+ out_ellipse = ""
+ else:
+ out_ellipse = ellipse_inds[-longest:]
+
+ if out_sub:
+ subscripts += "->" + output_sub.replace("...", out_ellipse)
+ else:
+ # Special care for outputless ellipses
+ output_subscript = ""
+ tmp_subscripts = subscripts.replace(",", "")
+ for s in sorted(set(tmp_subscripts)):
+ if s not in (einsum_symbols):
+ raise ValueError("Character %s is not a valid symbol." % s)
+ if tmp_subscripts.count(s) == 1:
+ output_subscript += s
+ normal_inds = ''.join(sorted(set(output_subscript) -
+ set(out_ellipse)))
+
+ subscripts += "->" + out_ellipse + normal_inds
+
+ # Build output string if does not exist
+ if "->" in subscripts:
+ input_subscripts, output_subscript = subscripts.split("->")
+ else:
+ input_subscripts = subscripts
+ # Build output subscripts
+ tmp_subscripts = subscripts.replace(",", "")
+ output_subscript = ""
+ for s in sorted(set(tmp_subscripts)):
+ if s not in einsum_symbols:
+ raise ValueError("Character %s is not a valid symbol." % s)
+ if tmp_subscripts.count(s) == 1:
+ output_subscript += s
+
+ # Make sure output subscripts are in the input
+ for char in output_subscript:
+ if output_subscript.count(char) != 1:
+ raise ValueError("Output character %s appeared more than once in "
+ "the output." % char)
+ if char not in input_subscripts:
+ raise ValueError("Output character %s did not appear in the input"
+ % char)
+
+ # Make sure number operands is equivalent to the number of terms
+ if len(input_subscripts.split(',')) != len(operands):
+ raise ValueError("Number of einsum subscripts must be equal to the "
+ "number of operands.")
+
+ return (input_subscripts, output_subscript, operands)
+
+
+def _einsum_path_dispatcher(*operands, optimize=None, einsum_call=None):
+ # NOTE: technically, we should only dispatch on array-like arguments, not
+ # subscripts (given as strings). But separating operands into
+ # arrays/subscripts is a little tricky/slow (given einsum's two supported
+ # signatures), so as a practical shortcut we dispatch on everything.
+ # Strings will be ignored for dispatching since they don't define
+ # __array_function__.
+ return operands
+
+
+@array_function_dispatch(_einsum_path_dispatcher, module='numpy')
+def einsum_path(*operands, optimize='greedy', einsum_call=False):
+ """
+ einsum_path(subscripts, *operands, optimize='greedy')
+
+ Evaluates the lowest cost contraction order for an einsum expression by
+ considering the creation of intermediate arrays.
+
+ Parameters
+ ----------
+ subscripts : str
+ Specifies the subscripts for summation.
+ *operands : list of array_like
+ These are the arrays for the operation.
+ optimize : {bool, list, tuple, 'greedy', 'optimal'}
+ Choose the type of path. If a tuple is provided, the second argument is
+ assumed to be the maximum intermediate size created. If only a single
+ argument is provided the largest input or output array size is used
+ as a maximum intermediate size.
+
+ * if a list is given that starts with ``einsum_path``, uses this as the
+ contraction path
+ * if False no optimization is taken
+ * if True defaults to the 'greedy' algorithm
+ * 'optimal' An algorithm that combinatorially explores all possible
+ ways of contracting the listed tensors and chooses the least costly
+ path. Scales exponentially with the number of terms in the
+ contraction.
+ * 'greedy' An algorithm that chooses the best pair contraction
+ at each step. Effectively, this algorithm searches the largest inner,
+ Hadamard, and then outer products at each step. Scales cubically with
+ the number of terms in the contraction. Equivalent to the 'optimal'
+ path for most contractions.
+
+ Default is 'greedy'.
+
+ Returns
+ -------
+ path : list of tuples
+ A list representation of the einsum path.
+ string_repr : str
+ A printable representation of the einsum path.
+
+ Notes
+ -----
+ The resulting path indicates which terms of the input contraction should be
+ contracted first, the result of this contraction is then appended to the
+ end of the contraction list. This list can then be iterated over until all
+ intermediate contractions are complete.
+
+ See Also
+ --------
+ einsum, linalg.multi_dot
+
+ Examples
+ --------
+
+ We can begin with a chain dot example. In this case, it is optimal to
+ contract the ``b`` and ``c`` tensors first as represented by the first
+ element of the path ``(1, 2)``. The resulting tensor is added to the end
+ of the contraction and the remaining contraction ``(0, 1)`` is then
+ completed.
+
+ >>> np.random.seed(123)
+ >>> a = np.random.rand(2, 2)
+ >>> b = np.random.rand(2, 5)
+ >>> c = np.random.rand(5, 2)
+ >>> path_info = np.einsum_path('ij,jk,kl->il', a, b, c, optimize='greedy')
+ >>> print(path_info[0])
+ ['einsum_path', (1, 2), (0, 1)]
+ >>> print(path_info[1])
+ Complete contraction: ij,jk,kl->il # may vary
+ Naive scaling: 4
+ Optimized scaling: 3
+ Naive FLOP count: 1.600e+02
+ Optimized FLOP count: 5.600e+01
+ Theoretical speedup: 2.857
+ Largest intermediate: 4.000e+00 elements
+ -------------------------------------------------------------------------
+ scaling current remaining
+ -------------------------------------------------------------------------
+ 3 kl,jk->jl ij,jl->il
+ 3 jl,ij->il il->il
+
+
+ A more complex index transformation example.
+
+ >>> I = np.random.rand(10, 10, 10, 10)
+ >>> C = np.random.rand(10, 10)
+ >>> path_info = np.einsum_path('ea,fb,abcd,gc,hd->efgh', C, C, I, C, C,
+ ... optimize='greedy')
+
+ >>> print(path_info[0])
+ ['einsum_path', (0, 2), (0, 3), (0, 2), (0, 1)]
+ >>> print(path_info[1])
+ Complete contraction: ea,fb,abcd,gc,hd->efgh # may vary
+ Naive scaling: 8
+ Optimized scaling: 5
+ Naive FLOP count: 8.000e+08
+ Optimized FLOP count: 8.000e+05
+ Theoretical speedup: 1000.000
+ Largest intermediate: 1.000e+04 elements
+ --------------------------------------------------------------------------
+ scaling current remaining
+ --------------------------------------------------------------------------
+ 5 abcd,ea->bcde fb,gc,hd,bcde->efgh
+ 5 bcde,fb->cdef gc,hd,cdef->efgh
+ 5 cdef,gc->defg hd,defg->efgh
+ 5 defg,hd->efgh efgh->efgh
+ """
+
+ # Figure out what the path really is
+ path_type = optimize
+ if path_type is True:
+ path_type = 'greedy'
+ if path_type is None:
+ path_type = False
+
+ explicit_einsum_path = False
+ memory_limit = None
+
+ # No optimization or a named path algorithm
+ if (path_type is False) or isinstance(path_type, str):
+ pass
+
+ # Given an explicit path
+ elif len(path_type) and (path_type[0] == 'einsum_path'):
+ explicit_einsum_path = True
+
+ # Path tuple with memory limit
+ elif ((len(path_type) == 2) and isinstance(path_type[0], str) and
+ isinstance(path_type[1], (int, float))):
+ memory_limit = int(path_type[1])
+ path_type = path_type[0]
+
+ else:
+ raise TypeError("Did not understand the path: %s" % str(path_type))
+
+ # Hidden option, only einsum should call this
+ einsum_call_arg = einsum_call
+
+ # Python side parsing
+ input_subscripts, output_subscript, operands = (
+ _parse_einsum_input(operands)
+ )
+
+ # Build a few useful list and sets
+ input_list = input_subscripts.split(',')
+ input_sets = [set(x) for x in input_list]
+ output_set = set(output_subscript)
+ indices = set(input_subscripts.replace(',', ''))
+
+ # Get length of each unique dimension and ensure all dimensions are correct
+ dimension_dict = {}
+ broadcast_indices = [[] for x in range(len(input_list))]
+ for tnum, term in enumerate(input_list):
+ sh = operands[tnum].shape
+ if len(sh) != len(term):
+ raise ValueError("Einstein sum subscript %s does not contain the "
+ "correct number of indices for operand %d."
+ % (input_subscripts[tnum], tnum))
+ for cnum, char in enumerate(term):
+ dim = sh[cnum]
+
+ # Build out broadcast indices
+ if dim == 1:
+ broadcast_indices[tnum].append(char)
+
+ if char in dimension_dict.keys():
+ # For broadcasting cases we always want the largest dim size
+ if dimension_dict[char] == 1:
+ dimension_dict[char] = dim
+ elif dim not in (1, dimension_dict[char]):
+ raise ValueError("Size of label '%s' for operand %d (%d) "
+ "does not match previous terms (%d)."
+ % (char, tnum, dimension_dict[char], dim))
+ else:
+ dimension_dict[char] = dim
+
+ # Convert broadcast inds to sets
+ broadcast_indices = [set(x) for x in broadcast_indices]
+
+ # Compute size of each input array plus the output array
+ size_list = [_compute_size_by_dict(term, dimension_dict)
+ for term in input_list + [output_subscript]]
+ max_size = max(size_list)
+
+ if memory_limit is None:
+ memory_arg = max_size
+ else:
+ memory_arg = memory_limit
+
+ # Compute naive cost
+ # This isn't quite right, need to look into exactly how einsum does this
+ inner_product = (sum(len(x) for x in input_sets) - len(indices)) > 0
+ naive_cost = _flop_count(
+ indices, inner_product, len(input_list), dimension_dict
+ )
+
+ # Compute the path
+ if explicit_einsum_path:
+ path = path_type[1:]
+ elif (
+ (path_type is False)
+ or (len(input_list) in [1, 2])
+ or (indices == output_set)
+ ):
+ # Nothing to be optimized, leave it to einsum
+ path = [tuple(range(len(input_list)))]
+ elif path_type == "greedy":
+ path = _greedy_path(
+ input_sets, output_set, dimension_dict, memory_arg
+ )
+ elif path_type == "optimal":
+ path = _optimal_path(
+ input_sets, output_set, dimension_dict, memory_arg
+ )
+ else:
+ raise KeyError("Path name %s not found", path_type)
+
+ cost_list, scale_list, size_list, contraction_list = [], [], [], []
+
+ # Build contraction tuple (positions, gemm, einsum_str, remaining)
+ for cnum, contract_inds in enumerate(path):
+ # Make sure we remove inds from right to left
+ contract_inds = tuple(sorted(contract_inds, reverse=True))
+
+ contract = _find_contraction(contract_inds, input_sets, output_set)
+ out_inds, input_sets, idx_removed, idx_contract = contract
+
+ cost = _flop_count(
+ idx_contract, idx_removed, len(contract_inds), dimension_dict
+ )
+ cost_list.append(cost)
+ scale_list.append(len(idx_contract))
+ size_list.append(_compute_size_by_dict(out_inds, dimension_dict))
+
+ bcast = set()
+ tmp_inputs = []
+ for x in contract_inds:
+ tmp_inputs.append(input_list.pop(x))
+ bcast |= broadcast_indices.pop(x)
+
+ new_bcast_inds = bcast - idx_removed
+
+ # If we're broadcasting, nix blas
+ if not len(idx_removed & bcast):
+ do_blas = _can_dot(tmp_inputs, out_inds, idx_removed)
+ else:
+ do_blas = False
+
+ # Last contraction
+ if (cnum - len(path)) == -1:
+ idx_result = output_subscript
+ else:
+ sort_result = [(dimension_dict[ind], ind) for ind in out_inds]
+ idx_result = "".join([x[1] for x in sorted(sort_result)])
+
+ input_list.append(idx_result)
+ broadcast_indices.append(new_bcast_inds)
+ einsum_str = ",".join(tmp_inputs) + "->" + idx_result
+
+ contraction = (
+ contract_inds, idx_removed, einsum_str, input_list[:], do_blas
+ )
+ contraction_list.append(contraction)
+
+ opt_cost = sum(cost_list) + 1
+
+ if len(input_list) != 1:
+ # Explicit "einsum_path" is usually trusted, but we detect this kind of
+ # mistake in order to prevent from returning an intermediate value.
+ raise RuntimeError(
+ "Invalid einsum_path is specified: {} more operands has to be "
+ "contracted.".format(len(input_list) - 1))
+
+ if einsum_call_arg:
+ return (operands, contraction_list)
+
+ # Return the path along with a nice string representation
+ overall_contraction = input_subscripts + "->" + output_subscript
+ header = ("scaling", "current", "remaining")
+
+ speedup = naive_cost / opt_cost
+ max_i = max(size_list)
+
+ path_print = " Complete contraction: %s\n" % overall_contraction
+ path_print += " Naive scaling: %d\n" % len(indices)
+ path_print += " Optimized scaling: %d\n" % max(scale_list)
+ path_print += " Naive FLOP count: %.3e\n" % naive_cost
+ path_print += " Optimized FLOP count: %.3e\n" % opt_cost
+ path_print += " Theoretical speedup: %3.3f\n" % speedup
+ path_print += " Largest intermediate: %.3e elements\n" % max_i
+ path_print += "-" * 74 + "\n"
+ path_print += "%6s %24s %40s\n" % header
+ path_print += "-" * 74
+
+ for n, contraction in enumerate(contraction_list):
+ inds, idx_rm, einsum_str, remaining, blas = contraction
+ remaining_str = ",".join(remaining) + "->" + output_subscript
+ path_run = (scale_list[n], einsum_str, remaining_str)
+ path_print += "\n%4d %24s %40s" % path_run
+
+ path = ['einsum_path'] + path
+ return (path, path_print)
+
+
+def _einsum_dispatcher(*operands, out=None, optimize=None, **kwargs):
+ # Arguably we dispatch on more arguments than we really should; see note in
+ # _einsum_path_dispatcher for why.
+ yield from operands
+ yield out
+
+
+# Rewrite einsum to handle different cases
+@array_function_dispatch(_einsum_dispatcher, module='numpy')
+def einsum(*operands, out=None, optimize=False, **kwargs):
+ """
+ einsum(subscripts, *operands, out=None, dtype=None, order='K',
+ casting='safe', optimize=False)
+
+ Evaluates the Einstein summation convention on the operands.
+
+ Using the Einstein summation convention, many common multi-dimensional,
+ linear algebraic array operations can be represented in a simple fashion.
+ In *implicit* mode `einsum` computes these values.
+
+ In *explicit* mode, `einsum` provides further flexibility to compute
+ other array operations that might not be considered classical Einstein
+ summation operations, by disabling, or forcing summation over specified
+ subscript labels.
+
+ See the notes and examples for clarification.
+
+ Parameters
+ ----------
+ subscripts : str
+ Specifies the subscripts for summation as comma separated list of
+ subscript labels. An implicit (classical Einstein summation)
+ calculation is performed unless the explicit indicator '->' is
+ included as well as subscript labels of the precise output form.
+ operands : list of array_like
+ These are the arrays for the operation.
+ out : ndarray, optional
+ If provided, the calculation is done into this array.
+ dtype : {data-type, None}, optional
+ If provided, forces the calculation to use the data type specified.
+ Note that you may have to also give a more liberal `casting`
+ parameter to allow the conversions. Default is None.
+ order : {'C', 'F', 'A', 'K'}, optional
+ Controls the memory layout of the output. 'C' means it should
+ be C contiguous. 'F' means it should be Fortran contiguous,
+ 'A' means it should be 'F' if the inputs are all 'F', 'C' otherwise.
+ 'K' means it should be as close to the layout as the inputs as
+ is possible, including arbitrarily permuted axes.
+ Default is 'K'.
+ casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
+ Controls what kind of data casting may occur. Setting this to
+ 'unsafe' is not recommended, as it can adversely affect accumulations.
+
+ * 'no' means the data types should not be cast at all.
+ * 'equiv' means only byte-order changes are allowed.
+ * 'safe' means only casts which can preserve values are allowed.
+ * 'same_kind' means only safe casts or casts within a kind,
+ like float64 to float32, are allowed.
+ * 'unsafe' means any data conversions may be done.
+
+ Default is 'safe'.
+ optimize : {False, True, 'greedy', 'optimal'}, optional
+ Controls if intermediate optimization should occur. No optimization
+ will occur if False and True will default to the 'greedy' algorithm.
+ Also accepts an explicit contraction list from the ``np.einsum_path``
+ function. See ``np.einsum_path`` for more details. Defaults to False.
+
+ Returns
+ -------
+ output : ndarray
+ The calculation based on the Einstein summation convention.
+
+ See Also
+ --------
+ einsum_path, dot, inner, outer, tensordot, linalg.multi_dot
+ einsum:
+ Similar verbose interface is provided by the
+ `einops `_ package to cover
+ additional operations: transpose, reshape/flatten, repeat/tile,
+ squeeze/unsqueeze and reductions.
+ The `opt_einsum `_
+ optimizes contraction order for einsum-like expressions
+ in backend-agnostic manner.
+
+ Notes
+ -----
+ The Einstein summation convention can be used to compute
+ many multi-dimensional, linear algebraic array operations. `einsum`
+ provides a succinct way of representing these.
+
+ A non-exhaustive list of these operations,
+ which can be computed by `einsum`, is shown below along with examples:
+
+ * Trace of an array, :py:func:`numpy.trace`.
+ * Return a diagonal, :py:func:`numpy.diag`.
+ * Array axis summations, :py:func:`numpy.sum`.
+ * Transpositions and permutations, :py:func:`numpy.transpose`.
+ * Matrix multiplication and dot product, :py:func:`numpy.matmul`
+ :py:func:`numpy.dot`.
+ * Vector inner and outer products, :py:func:`numpy.inner`
+ :py:func:`numpy.outer`.
+ * Broadcasting, element-wise and scalar multiplication,
+ :py:func:`numpy.multiply`.
+ * Tensor contractions, :py:func:`numpy.tensordot`.
+ * Chained array operations, in efficient calculation order,
+ :py:func:`numpy.einsum_path`.
+
+ The subscripts string is a comma-separated list of subscript labels,
+ where each label refers to a dimension of the corresponding operand.
+ Whenever a label is repeated it is summed, so ``np.einsum('i,i', a, b)``
+ is equivalent to :py:func:`np.inner(a,b) `. If a label
+ appears only once, it is not summed, so ``np.einsum('i', a)``
+ produces a view of ``a`` with no changes. A further example
+ ``np.einsum('ij,jk', a, b)`` describes traditional matrix multiplication
+ and is equivalent to :py:func:`np.matmul(a,b) `.
+ Repeated subscript labels in one operand take the diagonal.
+ For example, ``np.einsum('ii', a)`` is equivalent to
+ :py:func:`np.trace(a) `.
+
+ In *implicit mode*, the chosen subscripts are important
+ since the axes of the output are reordered alphabetically. This
+ means that ``np.einsum('ij', a)`` doesn't affect a 2D array, while
+ ``np.einsum('ji', a)`` takes its transpose. Additionally,
+ ``np.einsum('ij,jk', a, b)`` returns a matrix multiplication, while,
+ ``np.einsum('ij,jh', a, b)`` returns the transpose of the
+ multiplication since subscript 'h' precedes subscript 'i'.
+
+ In *explicit mode* the output can be directly controlled by
+ specifying output subscript labels. This requires the
+ identifier '->' as well as the list of output subscript labels.
+ This feature increases the flexibility of the function since
+ summing can be disabled or forced when required. The call
+ ``np.einsum('i->', a)`` is like :py:func:`np.sum(a) `
+ if ``a`` is a 1-D array, and ``np.einsum('ii->i', a)``
+ is like :py:func:`np.diag(a) ` if ``a`` is a square 2-D array.
+ The difference is that `einsum` does not allow broadcasting by default.
+ Additionally ``np.einsum('ij,jh->ih', a, b)`` directly specifies the
+ order of the output subscript labels and therefore returns matrix
+ multiplication, unlike the example above in implicit mode.
+
+ To enable and control broadcasting, use an ellipsis. Default
+ NumPy-style broadcasting is done by adding an ellipsis
+ to the left of each term, like ``np.einsum('...ii->...i', a)``.
+ ``np.einsum('...i->...', a)`` is like
+ :py:func:`np.sum(a, axis=-1) ` for array ``a`` of any shape.
+ To take the trace along the first and last axes,
+ you can do ``np.einsum('i...i', a)``, or to do a matrix-matrix
+ product with the left-most indices instead of rightmost, one can do
+ ``np.einsum('ij...,jk...->ik...', a, b)``.
+
+ When there is only one operand, no axes are summed, and no output
+ parameter is provided, a view into the operand is returned instead
+ of a new array. Thus, taking the diagonal as ``np.einsum('ii->i', a)``
+ produces a view (changed in version 1.10.0).
+
+ `einsum` also provides an alternative way to provide the subscripts and
+ operands as ``einsum(op0, sublist0, op1, sublist1, ..., [sublistout])``.
+ If the output shape is not provided in this format `einsum` will be
+ calculated in implicit mode, otherwise it will be performed explicitly.
+ The examples below have corresponding `einsum` calls with the two
+ parameter methods.
+
+ Views returned from einsum are now writeable whenever the input array
+ is writeable. For example, ``np.einsum('ijk...->kji...', a)`` will now
+ have the same effect as :py:func:`np.swapaxes(a, 0, 2) `
+ and ``np.einsum('ii->i', a)`` will return a writeable view of the diagonal
+ of a 2D array.
+
+ Added the ``optimize`` argument which will optimize the contraction order
+ of an einsum expression. For a contraction with three or more operands
+ this can greatly increase the computational efficiency at the cost of
+ a larger memory footprint during computation.
+
+ Typically a 'greedy' algorithm is applied which empirical tests have shown
+ returns the optimal path in the majority of cases. In some cases 'optimal'
+ will return the superlative path through a more expensive, exhaustive
+ search. For iterative calculations it may be advisable to calculate
+ the optimal path once and reuse that path by supplying it as an argument.
+ An example is given below.
+
+ See :py:func:`numpy.einsum_path` for more details.
+
+ Examples
+ --------
+ >>> a = np.arange(25).reshape(5,5)
+ >>> b = np.arange(5)
+ >>> c = np.arange(6).reshape(2,3)
+
+ Trace of a matrix:
+
+ >>> np.einsum('ii', a)
+ 60
+ >>> np.einsum(a, [0,0])
+ 60
+ >>> np.trace(a)
+ 60
+
+ Extract the diagonal (requires explicit form):
+
+ >>> np.einsum('ii->i', a)
+ array([ 0, 6, 12, 18, 24])
+ >>> np.einsum(a, [0,0], [0])
+ array([ 0, 6, 12, 18, 24])
+ >>> np.diag(a)
+ array([ 0, 6, 12, 18, 24])
+
+ Sum over an axis (requires explicit form):
+
+ >>> np.einsum('ij->i', a)
+ array([ 10, 35, 60, 85, 110])
+ >>> np.einsum(a, [0,1], [0])
+ array([ 10, 35, 60, 85, 110])
+ >>> np.sum(a, axis=1)
+ array([ 10, 35, 60, 85, 110])
+
+ For higher dimensional arrays summing a single axis can be done
+ with ellipsis:
+
+ >>> np.einsum('...j->...', a)
+ array([ 10, 35, 60, 85, 110])
+ >>> np.einsum(a, [Ellipsis,1], [Ellipsis])
+ array([ 10, 35, 60, 85, 110])
+
+ Compute a matrix transpose, or reorder any number of axes:
+
+ >>> np.einsum('ji', c)
+ array([[0, 3],
+ [1, 4],
+ [2, 5]])
+ >>> np.einsum('ij->ji', c)
+ array([[0, 3],
+ [1, 4],
+ [2, 5]])
+ >>> np.einsum(c, [1,0])
+ array([[0, 3],
+ [1, 4],
+ [2, 5]])
+ >>> np.transpose(c)
+ array([[0, 3],
+ [1, 4],
+ [2, 5]])
+
+ Vector inner products:
+
+ >>> np.einsum('i,i', b, b)
+ 30
+ >>> np.einsum(b, [0], b, [0])
+ 30
+ >>> np.inner(b,b)
+ 30
+
+ Matrix vector multiplication:
+
+ >>> np.einsum('ij,j', a, b)
+ array([ 30, 80, 130, 180, 230])
+ >>> np.einsum(a, [0,1], b, [1])
+ array([ 30, 80, 130, 180, 230])
+ >>> np.dot(a, b)
+ array([ 30, 80, 130, 180, 230])
+ >>> np.einsum('...j,j', a, b)
+ array([ 30, 80, 130, 180, 230])
+
+ Broadcasting and scalar multiplication:
+
+ >>> np.einsum('..., ...', 3, c)
+ array([[ 0, 3, 6],
+ [ 9, 12, 15]])
+ >>> np.einsum(',ij', 3, c)
+ array([[ 0, 3, 6],
+ [ 9, 12, 15]])
+ >>> np.einsum(3, [Ellipsis], c, [Ellipsis])
+ array([[ 0, 3, 6],
+ [ 9, 12, 15]])
+ >>> np.multiply(3, c)
+ array([[ 0, 3, 6],
+ [ 9, 12, 15]])
+
+ Vector outer product:
+
+ >>> np.einsum('i,j', np.arange(2)+1, b)
+ array([[0, 1, 2, 3, 4],
+ [0, 2, 4, 6, 8]])
+ >>> np.einsum(np.arange(2)+1, [0], b, [1])
+ array([[0, 1, 2, 3, 4],
+ [0, 2, 4, 6, 8]])
+ >>> np.outer(np.arange(2)+1, b)
+ array([[0, 1, 2, 3, 4],
+ [0, 2, 4, 6, 8]])
+
+ Tensor contraction:
+
+ >>> a = np.arange(60.).reshape(3,4,5)
+ >>> b = np.arange(24.).reshape(4,3,2)
+ >>> np.einsum('ijk,jil->kl', a, b)
+ array([[4400., 4730.],
+ [4532., 4874.],
+ [4664., 5018.],
+ [4796., 5162.],
+ [4928., 5306.]])
+ >>> np.einsum(a, [0,1,2], b, [1,0,3], [2,3])
+ array([[4400., 4730.],
+ [4532., 4874.],
+ [4664., 5018.],
+ [4796., 5162.],
+ [4928., 5306.]])
+ >>> np.tensordot(a,b, axes=([1,0],[0,1]))
+ array([[4400., 4730.],
+ [4532., 4874.],
+ [4664., 5018.],
+ [4796., 5162.],
+ [4928., 5306.]])
+
+ Writeable returned arrays (since version 1.10.0):
+
+ >>> a = np.zeros((3, 3))
+ >>> np.einsum('ii->i', a)[:] = 1
+ >>> a
+ array([[1., 0., 0.],
+ [0., 1., 0.],
+ [0., 0., 1.]])
+
+ Example of ellipsis use:
+
+ >>> a = np.arange(6).reshape((3,2))
+ >>> b = np.arange(12).reshape((4,3))
+ >>> np.einsum('ki,jk->ij', a, b)
+ array([[10, 28, 46, 64],
+ [13, 40, 67, 94]])
+ >>> np.einsum('ki,...k->i...', a, b)
+ array([[10, 28, 46, 64],
+ [13, 40, 67, 94]])
+ >>> np.einsum('k...,jk', a, b)
+ array([[10, 28, 46, 64],
+ [13, 40, 67, 94]])
+
+ Chained array operations. For more complicated contractions, speed ups
+ might be achieved by repeatedly computing a 'greedy' path or pre-computing
+ the 'optimal' path and repeatedly applying it, using an `einsum_path`
+ insertion (since version 1.12.0). Performance improvements can be
+ particularly significant with larger arrays:
+
+ >>> a = np.ones(64).reshape(2,4,8)
+
+ Basic `einsum`: ~1520ms (benchmarked on 3.1GHz Intel i5.)
+
+ >>> for iteration in range(500):
+ ... _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a)
+
+ Sub-optimal `einsum` (due to repeated path calculation time): ~330ms
+
+ >>> for iteration in range(500):
+ ... _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a,
+ ... optimize='optimal')
+
+ Greedy `einsum` (faster optimal path approximation): ~160ms
+
+ >>> for iteration in range(500):
+ ... _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, optimize='greedy')
+
+ Optimal `einsum` (best usage pattern in some use cases): ~110ms
+
+ >>> path = np.einsum_path('ijk,ilm,njm,nlk,abc->',a,a,a,a,a,
+ ... optimize='optimal')[0]
+ >>> for iteration in range(500):
+ ... _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, optimize=path)
+
+ """
+ # Special handling if out is specified
+ specified_out = out is not None
+
+ # If no optimization, run pure einsum
+ if optimize is False:
+ if specified_out:
+ kwargs['out'] = out
+ return c_einsum(*operands, **kwargs)
+
+ # Check the kwargs to avoid a more cryptic error later, without having to
+ # repeat default values here
+ valid_einsum_kwargs = ['dtype', 'order', 'casting']
+ unknown_kwargs = [k for (k, v) in kwargs.items() if
+ k not in valid_einsum_kwargs]
+ if len(unknown_kwargs):
+ raise TypeError("Did not understand the following kwargs: %s"
+ % unknown_kwargs)
+
+ # Build the contraction list and operand
+ operands, contraction_list = einsum_path(*operands, optimize=optimize,
+ einsum_call=True)
+
+ # Handle order kwarg for output array, c_einsum allows mixed case
+ output_order = kwargs.pop('order', 'K')
+ if output_order.upper() == 'A':
+ if all(arr.flags.f_contiguous for arr in operands):
+ output_order = 'F'
+ else:
+ output_order = 'C'
+
+ # Start contraction loop
+ for num, contraction in enumerate(contraction_list):
+ inds, idx_rm, einsum_str, remaining, blas = contraction
+ tmp_operands = [operands.pop(x) for x in inds]
+
+ # Do we need to deal with the output?
+ handle_out = specified_out and ((num + 1) == len(contraction_list))
+
+ # Call tensordot if still possible
+ if blas:
+ # Checks have already been handled
+ input_str, results_index = einsum_str.split('->')
+ input_left, input_right = input_str.split(',')
+
+ tensor_result = input_left + input_right
+ for s in idx_rm:
+ tensor_result = tensor_result.replace(s, "")
+
+ # Find indices to contract over
+ left_pos, right_pos = [], []
+ for s in sorted(idx_rm):
+ left_pos.append(input_left.find(s))
+ right_pos.append(input_right.find(s))
+
+ # Contract!
+ new_view = tensordot(
+ *tmp_operands, axes=(tuple(left_pos), tuple(right_pos))
+ )
+
+ # Build a new view if needed
+ if (tensor_result != results_index) or handle_out:
+ if handle_out:
+ kwargs["out"] = out
+ new_view = c_einsum(
+ tensor_result + '->' + results_index, new_view, **kwargs
+ )
+
+ # Call einsum
+ else:
+ # If out was specified
+ if handle_out:
+ kwargs["out"] = out
+
+ # Do the contraction
+ new_view = c_einsum(einsum_str, *tmp_operands, **kwargs)
+
+ # Append new items and dereference what we can
+ operands.append(new_view)
+ del tmp_operands, new_view
+
+ if specified_out:
+ return out
+ else:
+ return asanyarray(operands[0], order=output_order)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/einsumfunc.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/einsumfunc.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..00629a478c25a69749ff4479570123891e49d392
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/einsumfunc.pyi
@@ -0,0 +1,185 @@
+from collections.abc import Sequence
+from typing import TypeAlias, TypeVar, Any, overload, Literal
+
+import numpy as np
+from numpy import number, _OrderKACF
+from numpy._typing import (
+ NDArray,
+ _ArrayLikeBool_co,
+ _ArrayLikeUInt_co,
+ _ArrayLikeInt_co,
+ _ArrayLikeFloat_co,
+ _ArrayLikeComplex_co,
+ _ArrayLikeObject_co,
+ _DTypeLikeBool,
+ _DTypeLikeUInt,
+ _DTypeLikeInt,
+ _DTypeLikeFloat,
+ _DTypeLikeComplex,
+ _DTypeLikeComplex_co,
+ _DTypeLikeObject,
+)
+
+__all__ = ["einsum", "einsum_path"]
+
+_ArrayType = TypeVar(
+ "_ArrayType",
+ bound=NDArray[np.bool | number[Any]],
+)
+
+_OptimizeKind: TypeAlias = bool | Literal["greedy", "optimal"] | Sequence[Any] | None
+_CastingSafe: TypeAlias = Literal["no", "equiv", "safe", "same_kind"]
+_CastingUnsafe: TypeAlias = Literal["unsafe"]
+
+
+# TODO: Properly handle the `casting`-based combinatorics
+# TODO: We need to evaluate the content `__subscripts` in order
+# to identify whether or an array or scalar is returned. At a cursory
+# glance this seems like something that can quite easily be done with
+# a mypy plugin.
+# Something like `is_scalar = bool(__subscripts.partition("->")[-1])`
+@overload
+def einsum(
+ subscripts: str | _ArrayLikeInt_co,
+ /,
+ *operands: _ArrayLikeBool_co,
+ out: None = ...,
+ dtype: None | _DTypeLikeBool = ...,
+ order: _OrderKACF = ...,
+ casting: _CastingSafe = ...,
+ optimize: _OptimizeKind = ...,
+) -> Any: ...
+@overload
+def einsum(
+ subscripts: str | _ArrayLikeInt_co,
+ /,
+ *operands: _ArrayLikeUInt_co,
+ out: None = ...,
+ dtype: None | _DTypeLikeUInt = ...,
+ order: _OrderKACF = ...,
+ casting: _CastingSafe = ...,
+ optimize: _OptimizeKind = ...,
+) -> Any: ...
+@overload
+def einsum(
+ subscripts: str | _ArrayLikeInt_co,
+ /,
+ *operands: _ArrayLikeInt_co,
+ out: None = ...,
+ dtype: None | _DTypeLikeInt = ...,
+ order: _OrderKACF = ...,
+ casting: _CastingSafe = ...,
+ optimize: _OptimizeKind = ...,
+) -> Any: ...
+@overload
+def einsum(
+ subscripts: str | _ArrayLikeInt_co,
+ /,
+ *operands: _ArrayLikeFloat_co,
+ out: None = ...,
+ dtype: None | _DTypeLikeFloat = ...,
+ order: _OrderKACF = ...,
+ casting: _CastingSafe = ...,
+ optimize: _OptimizeKind = ...,
+) -> Any: ...
+@overload
+def einsum(
+ subscripts: str | _ArrayLikeInt_co,
+ /,
+ *operands: _ArrayLikeComplex_co,
+ out: None = ...,
+ dtype: None | _DTypeLikeComplex = ...,
+ order: _OrderKACF = ...,
+ casting: _CastingSafe = ...,
+ optimize: _OptimizeKind = ...,
+) -> Any: ...
+@overload
+def einsum(
+ subscripts: str | _ArrayLikeInt_co,
+ /,
+ *operands: Any,
+ casting: _CastingUnsafe,
+ dtype: None | _DTypeLikeComplex_co = ...,
+ out: None = ...,
+ order: _OrderKACF = ...,
+ optimize: _OptimizeKind = ...,
+) -> Any: ...
+@overload
+def einsum(
+ subscripts: str | _ArrayLikeInt_co,
+ /,
+ *operands: _ArrayLikeComplex_co,
+ out: _ArrayType,
+ dtype: None | _DTypeLikeComplex_co = ...,
+ order: _OrderKACF = ...,
+ casting: _CastingSafe = ...,
+ optimize: _OptimizeKind = ...,
+) -> _ArrayType: ...
+@overload
+def einsum(
+ subscripts: str | _ArrayLikeInt_co,
+ /,
+ *operands: Any,
+ out: _ArrayType,
+ casting: _CastingUnsafe,
+ dtype: None | _DTypeLikeComplex_co = ...,
+ order: _OrderKACF = ...,
+ optimize: _OptimizeKind = ...,
+) -> _ArrayType: ...
+
+@overload
+def einsum(
+ subscripts: str | _ArrayLikeInt_co,
+ /,
+ *operands: _ArrayLikeObject_co,
+ out: None = ...,
+ dtype: None | _DTypeLikeObject = ...,
+ order: _OrderKACF = ...,
+ casting: _CastingSafe = ...,
+ optimize: _OptimizeKind = ...,
+) -> Any: ...
+@overload
+def einsum(
+ subscripts: str | _ArrayLikeInt_co,
+ /,
+ *operands: Any,
+ casting: _CastingUnsafe,
+ dtype: None | _DTypeLikeObject = ...,
+ out: None = ...,
+ order: _OrderKACF = ...,
+ optimize: _OptimizeKind = ...,
+) -> Any: ...
+@overload
+def einsum(
+ subscripts: str | _ArrayLikeInt_co,
+ /,
+ *operands: _ArrayLikeObject_co,
+ out: _ArrayType,
+ dtype: None | _DTypeLikeObject = ...,
+ order: _OrderKACF = ...,
+ casting: _CastingSafe = ...,
+ optimize: _OptimizeKind = ...,
+) -> _ArrayType: ...
+@overload
+def einsum(
+ subscripts: str | _ArrayLikeInt_co,
+ /,
+ *operands: Any,
+ out: _ArrayType,
+ casting: _CastingUnsafe,
+ dtype: None | _DTypeLikeObject = ...,
+ order: _OrderKACF = ...,
+ optimize: _OptimizeKind = ...,
+) -> _ArrayType: ...
+
+# NOTE: `einsum_call` is a hidden kwarg unavailable for public use.
+# It is therefore excluded from the signatures below.
+# NOTE: In practice the list consists of a `str` (first element)
+# and a variable number of integer tuples.
+def einsum_path(
+ subscripts: str | _ArrayLikeInt_co,
+ /,
+ *operands: _ArrayLikeComplex_co | _DTypeLikeObject,
+ optimize: _OptimizeKind = "greedy",
+ einsum_call: Literal[False] = False,
+) -> tuple[list[Any], str]: ...
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/fromnumeric.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/fromnumeric.py
new file mode 100644
index 0000000000000000000000000000000000000000..202bcde9e5701e4f98a540af31b87f4b57e6b2c1
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/fromnumeric.py
@@ -0,0 +1,4269 @@
+"""Module containing non-deprecated functions borrowed from Numeric.
+
+"""
+import functools
+import types
+import warnings
+
+import numpy as np
+from .._utils import set_module
+from . import multiarray as mu
+from . import overrides
+from . import umath as um
+from . import numerictypes as nt
+from .multiarray import asarray, array, asanyarray, concatenate
+from ._multiarray_umath import _array_converter
+from . import _methods
+
+_dt_ = nt.sctype2char
+
+# functions that are methods
+__all__ = [
+ 'all', 'amax', 'amin', 'any', 'argmax',
+ 'argmin', 'argpartition', 'argsort', 'around', 'choose', 'clip',
+ 'compress', 'cumprod', 'cumsum', 'cumulative_prod', 'cumulative_sum',
+ 'diagonal', 'mean', 'max', 'min', 'matrix_transpose',
+ 'ndim', 'nonzero', 'partition', 'prod', 'ptp', 'put',
+ 'ravel', 'repeat', 'reshape', 'resize', 'round',
+ 'searchsorted', 'shape', 'size', 'sort', 'squeeze',
+ 'std', 'sum', 'swapaxes', 'take', 'trace', 'transpose', 'var',
+]
+
+_gentype = types.GeneratorType
+# save away Python sum
+_sum_ = sum
+
+array_function_dispatch = functools.partial(
+ overrides.array_function_dispatch, module='numpy')
+
+
+# functions that are now methods
+def _wrapit(obj, method, *args, **kwds):
+ conv = _array_converter(obj)
+ # As this already tried the method, subok is maybe quite reasonable here
+ # but this follows what was done before. TODO: revisit this.
+ arr, = conv.as_arrays(subok=False)
+ result = getattr(arr, method)(*args, **kwds)
+
+ return conv.wrap(result, to_scalar=False)
+
+
+def _wrapfunc(obj, method, *args, **kwds):
+ bound = getattr(obj, method, None)
+ if bound is None:
+ return _wrapit(obj, method, *args, **kwds)
+
+ try:
+ return bound(*args, **kwds)
+ except TypeError:
+ # A TypeError occurs if the object does have such a method in its
+ # class, but its signature is not identical to that of NumPy's. This
+ # situation has occurred in the case of a downstream library like
+ # 'pandas'.
+ #
+ # Call _wrapit from within the except clause to ensure a potential
+ # exception has a traceback chain.
+ return _wrapit(obj, method, *args, **kwds)
+
+
+def _wrapreduction(obj, ufunc, method, axis, dtype, out, **kwargs):
+ passkwargs = {k: v for k, v in kwargs.items()
+ if v is not np._NoValue}
+
+ if type(obj) is not mu.ndarray:
+ try:
+ reduction = getattr(obj, method)
+ except AttributeError:
+ pass
+ else:
+ # This branch is needed for reductions like any which don't
+ # support a dtype.
+ if dtype is not None:
+ return reduction(axis=axis, dtype=dtype, out=out, **passkwargs)
+ else:
+ return reduction(axis=axis, out=out, **passkwargs)
+
+ return ufunc.reduce(obj, axis, dtype, out, **passkwargs)
+
+
+def _wrapreduction_any_all(obj, ufunc, method, axis, out, **kwargs):
+ # Same as above function, but dtype is always bool (but never passed on)
+ passkwargs = {k: v for k, v in kwargs.items()
+ if v is not np._NoValue}
+
+ if type(obj) is not mu.ndarray:
+ try:
+ reduction = getattr(obj, method)
+ except AttributeError:
+ pass
+ else:
+ return reduction(axis=axis, out=out, **passkwargs)
+
+ return ufunc.reduce(obj, axis, bool, out, **passkwargs)
+
+
+def _take_dispatcher(a, indices, axis=None, out=None, mode=None):
+ return (a, out)
+
+
+@array_function_dispatch(_take_dispatcher)
+def take(a, indices, axis=None, out=None, mode='raise'):
+ """
+ Take elements from an array along an axis.
+
+ When axis is not None, this function does the same thing as "fancy"
+ indexing (indexing arrays using arrays); however, it can be easier to use
+ if you need elements along a given axis. A call such as
+ ``np.take(arr, indices, axis=3)`` is equivalent to
+ ``arr[:,:,:,indices,...]``.
+
+ Explained without fancy indexing, this is equivalent to the following use
+ of `ndindex`, which sets each of ``ii``, ``jj``, and ``kk`` to a tuple of
+ indices::
+
+ Ni, Nk = a.shape[:axis], a.shape[axis+1:]
+ Nj = indices.shape
+ for ii in ndindex(Ni):
+ for jj in ndindex(Nj):
+ for kk in ndindex(Nk):
+ out[ii + jj + kk] = a[ii + (indices[jj],) + kk]
+
+ Parameters
+ ----------
+ a : array_like (Ni..., M, Nk...)
+ The source array.
+ indices : array_like (Nj...)
+ The indices of the values to extract.
+ Also allow scalars for indices.
+ axis : int, optional
+ The axis over which to select values. By default, the flattened
+ input array is used.
+ out : ndarray, optional (Ni..., Nj..., Nk...)
+ If provided, the result will be placed in this array. It should
+ be of the appropriate shape and dtype. Note that `out` is always
+ buffered if `mode='raise'`; use other modes for better performance.
+ mode : {'raise', 'wrap', 'clip'}, optional
+ Specifies how out-of-bounds indices will behave.
+
+ * 'raise' -- raise an error (default)
+ * 'wrap' -- wrap around
+ * 'clip' -- clip to the range
+
+ 'clip' mode means that all indices that are too large are replaced
+ by the index that addresses the last element along that axis. Note
+ that this disables indexing with negative numbers.
+
+ Returns
+ -------
+ out : ndarray (Ni..., Nj..., Nk...)
+ The returned array has the same type as `a`.
+
+ See Also
+ --------
+ compress : Take elements using a boolean mask
+ ndarray.take : equivalent method
+ take_along_axis : Take elements by matching the array and the index arrays
+
+ Notes
+ -----
+ By eliminating the inner loop in the description above, and using `s_` to
+ build simple slice objects, `take` can be expressed in terms of applying
+ fancy indexing to each 1-d slice::
+
+ Ni, Nk = a.shape[:axis], a.shape[axis+1:]
+ for ii in ndindex(Ni):
+ for kk in ndindex(Nj):
+ out[ii + s_[...,] + kk] = a[ii + s_[:,] + kk][indices]
+
+ For this reason, it is equivalent to (but faster than) the following use
+ of `apply_along_axis`::
+
+ out = np.apply_along_axis(lambda a_1d: a_1d[indices], axis, a)
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = [4, 3, 5, 7, 6, 8]
+ >>> indices = [0, 1, 4]
+ >>> np.take(a, indices)
+ array([4, 3, 6])
+
+ In this example if `a` is an ndarray, "fancy" indexing can be used.
+
+ >>> a = np.array(a)
+ >>> a[indices]
+ array([4, 3, 6])
+
+ If `indices` is not one dimensional, the output also has these dimensions.
+
+ >>> np.take(a, [[0, 1], [2, 3]])
+ array([[4, 3],
+ [5, 7]])
+ """
+ return _wrapfunc(a, 'take', indices, axis=axis, out=out, mode=mode)
+
+
+def _reshape_dispatcher(a, /, shape=None, order=None, *, newshape=None,
+ copy=None):
+ return (a,)
+
+
+@array_function_dispatch(_reshape_dispatcher)
+def reshape(a, /, shape=None, order='C', *, newshape=None, copy=None):
+ """
+ Gives a new shape to an array without changing its data.
+
+ Parameters
+ ----------
+ a : array_like
+ Array to be reshaped.
+ shape : int or tuple of ints
+ The new shape should be compatible with the original shape. If
+ an integer, then the result will be a 1-D array of that length.
+ One shape dimension can be -1. In this case, the value is
+ inferred from the length of the array and remaining dimensions.
+ order : {'C', 'F', 'A'}, optional
+ Read the elements of ``a`` using this index order, and place the
+ elements into the reshaped array using this index order. 'C'
+ means to read / write the elements using C-like index order,
+ with the last axis index changing fastest, back to the first
+ axis index changing slowest. 'F' means to read / write the
+ elements using Fortran-like index order, with the first index
+ changing fastest, and the last index changing slowest. Note that
+ the 'C' and 'F' options take no account of the memory layout of
+ the underlying array, and only refer to the order of indexing.
+ 'A' means to read / write the elements in Fortran-like index
+ order if ``a`` is Fortran *contiguous* in memory, C-like order
+ otherwise.
+ newshape : int or tuple of ints
+ .. deprecated:: 2.1
+ Replaced by ``shape`` argument. Retained for backward
+ compatibility.
+ copy : bool, optional
+ If ``True``, then the array data is copied. If ``None``, a copy will
+ only be made if it's required by ``order``. For ``False`` it raises
+ a ``ValueError`` if a copy cannot be avoided. Default: ``None``.
+
+ Returns
+ -------
+ reshaped_array : ndarray
+ This will be a new view object if possible; otherwise, it will
+ be a copy. Note there is no guarantee of the *memory layout* (C- or
+ Fortran- contiguous) of the returned array.
+
+ See Also
+ --------
+ ndarray.reshape : Equivalent method.
+
+ Notes
+ -----
+ It is not always possible to change the shape of an array without copying
+ the data.
+
+ The ``order`` keyword gives the index ordering both for *fetching*
+ the values from ``a``, and then *placing* the values into the output
+ array. For example, let's say you have an array:
+
+ >>> a = np.arange(6).reshape((3, 2))
+ >>> a
+ array([[0, 1],
+ [2, 3],
+ [4, 5]])
+
+ You can think of reshaping as first raveling the array (using the given
+ index order), then inserting the elements from the raveled array into the
+ new array using the same kind of index ordering as was used for the
+ raveling.
+
+ >>> np.reshape(a, (2, 3)) # C-like index ordering
+ array([[0, 1, 2],
+ [3, 4, 5]])
+ >>> np.reshape(np.ravel(a), (2, 3)) # equivalent to C ravel then C reshape
+ array([[0, 1, 2],
+ [3, 4, 5]])
+ >>> np.reshape(a, (2, 3), order='F') # Fortran-like index ordering
+ array([[0, 4, 3],
+ [2, 1, 5]])
+ >>> np.reshape(np.ravel(a, order='F'), (2, 3), order='F')
+ array([[0, 4, 3],
+ [2, 1, 5]])
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[1,2,3], [4,5,6]])
+ >>> np.reshape(a, 6)
+ array([1, 2, 3, 4, 5, 6])
+ >>> np.reshape(a, 6, order='F')
+ array([1, 4, 2, 5, 3, 6])
+
+ >>> np.reshape(a, (3,-1)) # the unspecified value is inferred to be 2
+ array([[1, 2],
+ [3, 4],
+ [5, 6]])
+ """
+ if newshape is None and shape is None:
+ raise TypeError(
+ "reshape() missing 1 required positional argument: 'shape'")
+ if newshape is not None:
+ if shape is not None:
+ raise TypeError(
+ "You cannot specify 'newshape' and 'shape' arguments "
+ "at the same time.")
+ # Deprecated in NumPy 2.1, 2024-04-18
+ warnings.warn(
+ "`newshape` keyword argument is deprecated, "
+ "use `shape=...` or pass shape positionally instead. "
+ "(deprecated in NumPy 2.1)",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ shape = newshape
+ if copy is not None:
+ return _wrapfunc(a, 'reshape', shape, order=order, copy=copy)
+ return _wrapfunc(a, 'reshape', shape, order=order)
+
+
+def _choose_dispatcher(a, choices, out=None, mode=None):
+ yield a
+ yield from choices
+ yield out
+
+
+@array_function_dispatch(_choose_dispatcher)
+def choose(a, choices, out=None, mode='raise'):
+ """
+ Construct an array from an index array and a list of arrays to choose from.
+
+ First of all, if confused or uncertain, definitely look at the Examples -
+ in its full generality, this function is less simple than it might
+ seem from the following code description::
+
+ np.choose(a,c) == np.array([c[a[I]][I] for I in np.ndindex(a.shape)])
+
+ But this omits some subtleties. Here is a fully general summary:
+
+ Given an "index" array (`a`) of integers and a sequence of ``n`` arrays
+ (`choices`), `a` and each choice array are first broadcast, as necessary,
+ to arrays of a common shape; calling these *Ba* and *Bchoices[i], i =
+ 0,...,n-1* we have that, necessarily, ``Ba.shape == Bchoices[i].shape``
+ for each ``i``. Then, a new array with shape ``Ba.shape`` is created as
+ follows:
+
+ * if ``mode='raise'`` (the default), then, first of all, each element of
+ ``a`` (and thus ``Ba``) must be in the range ``[0, n-1]``; now, suppose
+ that ``i`` (in that range) is the value at the ``(j0, j1, ..., jm)``
+ position in ``Ba`` - then the value at the same position in the new array
+ is the value in ``Bchoices[i]`` at that same position;
+
+ * if ``mode='wrap'``, values in `a` (and thus `Ba`) may be any (signed)
+ integer; modular arithmetic is used to map integers outside the range
+ `[0, n-1]` back into that range; and then the new array is constructed
+ as above;
+
+ * if ``mode='clip'``, values in `a` (and thus ``Ba``) may be any (signed)
+ integer; negative integers are mapped to 0; values greater than ``n-1``
+ are mapped to ``n-1``; and then the new array is constructed as above.
+
+ Parameters
+ ----------
+ a : int array
+ This array must contain integers in ``[0, n-1]``, where ``n`` is the
+ number of choices, unless ``mode=wrap`` or ``mode=clip``, in which
+ cases any integers are permissible.
+ choices : sequence of arrays
+ Choice arrays. `a` and all of the choices must be broadcastable to the
+ same shape. If `choices` is itself an array (not recommended), then
+ its outermost dimension (i.e., the one corresponding to
+ ``choices.shape[0]``) is taken as defining the "sequence".
+ out : array, optional
+ If provided, the result will be inserted into this array. It should
+ be of the appropriate shape and dtype. Note that `out` is always
+ buffered if ``mode='raise'``; use other modes for better performance.
+ mode : {'raise' (default), 'wrap', 'clip'}, optional
+ Specifies how indices outside ``[0, n-1]`` will be treated:
+
+ * 'raise' : an exception is raised
+ * 'wrap' : value becomes value mod ``n``
+ * 'clip' : values < 0 are mapped to 0, values > n-1 are mapped to n-1
+
+ Returns
+ -------
+ merged_array : array
+ The merged result.
+
+ Raises
+ ------
+ ValueError: shape mismatch
+ If `a` and each choice array are not all broadcastable to the same
+ shape.
+
+ See Also
+ --------
+ ndarray.choose : equivalent method
+ numpy.take_along_axis : Preferable if `choices` is an array
+
+ Notes
+ -----
+ To reduce the chance of misinterpretation, even though the following
+ "abuse" is nominally supported, `choices` should neither be, nor be
+ thought of as, a single array, i.e., the outermost sequence-like container
+ should be either a list or a tuple.
+
+ Examples
+ --------
+
+ >>> import numpy as np
+ >>> choices = [[0, 1, 2, 3], [10, 11, 12, 13],
+ ... [20, 21, 22, 23], [30, 31, 32, 33]]
+ >>> np.choose([2, 3, 1, 0], choices
+ ... # the first element of the result will be the first element of the
+ ... # third (2+1) "array" in choices, namely, 20; the second element
+ ... # will be the second element of the fourth (3+1) choice array, i.e.,
+ ... # 31, etc.
+ ... )
+ array([20, 31, 12, 3])
+ >>> np.choose([2, 4, 1, 0], choices, mode='clip') # 4 goes to 3 (4-1)
+ array([20, 31, 12, 3])
+ >>> # because there are 4 choice arrays
+ >>> np.choose([2, 4, 1, 0], choices, mode='wrap') # 4 goes to (4 mod 4)
+ array([20, 1, 12, 3])
+ >>> # i.e., 0
+
+ A couple examples illustrating how choose broadcasts:
+
+ >>> a = [[1, 0, 1], [0, 1, 0], [1, 0, 1]]
+ >>> choices = [-10, 10]
+ >>> np.choose(a, choices)
+ array([[ 10, -10, 10],
+ [-10, 10, -10],
+ [ 10, -10, 10]])
+
+ >>> # With thanks to Anne Archibald
+ >>> a = np.array([0, 1]).reshape((2,1,1))
+ >>> c1 = np.array([1, 2, 3]).reshape((1,3,1))
+ >>> c2 = np.array([-1, -2, -3, -4, -5]).reshape((1,1,5))
+ >>> np.choose(a, (c1, c2)) # result is 2x3x5, res[0,:,:]=c1, res[1,:,:]=c2
+ array([[[ 1, 1, 1, 1, 1],
+ [ 2, 2, 2, 2, 2],
+ [ 3, 3, 3, 3, 3]],
+ [[-1, -2, -3, -4, -5],
+ [-1, -2, -3, -4, -5],
+ [-1, -2, -3, -4, -5]]])
+
+ """
+ return _wrapfunc(a, 'choose', choices, out=out, mode=mode)
+
+
+def _repeat_dispatcher(a, repeats, axis=None):
+ return (a,)
+
+
+@array_function_dispatch(_repeat_dispatcher)
+def repeat(a, repeats, axis=None):
+ """
+ Repeat each element of an array after themselves
+
+ Parameters
+ ----------
+ a : array_like
+ Input array.
+ repeats : int or array of ints
+ The number of repetitions for each element. `repeats` is broadcasted
+ to fit the shape of the given axis.
+ axis : int, optional
+ The axis along which to repeat values. By default, use the
+ flattened input array, and return a flat output array.
+
+ Returns
+ -------
+ repeated_array : ndarray
+ Output array which has the same shape as `a`, except along
+ the given axis.
+
+ See Also
+ --------
+ tile : Tile an array.
+ unique : Find the unique elements of an array.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.repeat(3, 4)
+ array([3, 3, 3, 3])
+ >>> x = np.array([[1,2],[3,4]])
+ >>> np.repeat(x, 2)
+ array([1, 1, 2, 2, 3, 3, 4, 4])
+ >>> np.repeat(x, 3, axis=1)
+ array([[1, 1, 1, 2, 2, 2],
+ [3, 3, 3, 4, 4, 4]])
+ >>> np.repeat(x, [1, 2], axis=0)
+ array([[1, 2],
+ [3, 4],
+ [3, 4]])
+
+ """
+ return _wrapfunc(a, 'repeat', repeats, axis=axis)
+
+
+def _put_dispatcher(a, ind, v, mode=None):
+ return (a, ind, v)
+
+
+@array_function_dispatch(_put_dispatcher)
+def put(a, ind, v, mode='raise'):
+ """
+ Replaces specified elements of an array with given values.
+
+ The indexing works on the flattened target array. `put` is roughly
+ equivalent to:
+
+ ::
+
+ a.flat[ind] = v
+
+ Parameters
+ ----------
+ a : ndarray
+ Target array.
+ ind : array_like
+ Target indices, interpreted as integers.
+ v : array_like
+ Values to place in `a` at target indices. If `v` is shorter than
+ `ind` it will be repeated as necessary.
+ mode : {'raise', 'wrap', 'clip'}, optional
+ Specifies how out-of-bounds indices will behave.
+
+ * 'raise' -- raise an error (default)
+ * 'wrap' -- wrap around
+ * 'clip' -- clip to the range
+
+ 'clip' mode means that all indices that are too large are replaced
+ by the index that addresses the last element along that axis. Note
+ that this disables indexing with negative numbers. In 'raise' mode,
+ if an exception occurs the target array may still be modified.
+
+ See Also
+ --------
+ putmask, place
+ put_along_axis : Put elements by matching the array and the index arrays
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.arange(5)
+ >>> np.put(a, [0, 2], [-44, -55])
+ >>> a
+ array([-44, 1, -55, 3, 4])
+
+ >>> a = np.arange(5)
+ >>> np.put(a, 22, -5, mode='clip')
+ >>> a
+ array([ 0, 1, 2, 3, -5])
+
+ """
+ try:
+ put = a.put
+ except AttributeError as e:
+ raise TypeError("argument 1 must be numpy.ndarray, "
+ "not {name}".format(name=type(a).__name__)) from e
+
+ return put(ind, v, mode=mode)
+
+
+def _swapaxes_dispatcher(a, axis1, axis2):
+ return (a,)
+
+
+@array_function_dispatch(_swapaxes_dispatcher)
+def swapaxes(a, axis1, axis2):
+ """
+ Interchange two axes of an array.
+
+ Parameters
+ ----------
+ a : array_like
+ Input array.
+ axis1 : int
+ First axis.
+ axis2 : int
+ Second axis.
+
+ Returns
+ -------
+ a_swapped : ndarray
+ For NumPy >= 1.10.0, if `a` is an ndarray, then a view of `a` is
+ returned; otherwise a new array is created. For earlier NumPy
+ versions a view of `a` is returned only if the order of the
+ axes is changed, otherwise the input array is returned.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.array([[1,2,3]])
+ >>> np.swapaxes(x,0,1)
+ array([[1],
+ [2],
+ [3]])
+
+ >>> x = np.array([[[0,1],[2,3]],[[4,5],[6,7]]])
+ >>> x
+ array([[[0, 1],
+ [2, 3]],
+ [[4, 5],
+ [6, 7]]])
+
+ >>> np.swapaxes(x,0,2)
+ array([[[0, 4],
+ [2, 6]],
+ [[1, 5],
+ [3, 7]]])
+
+ """
+ return _wrapfunc(a, 'swapaxes', axis1, axis2)
+
+
+def _transpose_dispatcher(a, axes=None):
+ return (a,)
+
+
+@array_function_dispatch(_transpose_dispatcher)
+def transpose(a, axes=None):
+ """
+ Returns an array with axes transposed.
+
+ For a 1-D array, this returns an unchanged view of the original array, as a
+ transposed vector is simply the same vector.
+ To convert a 1-D array into a 2-D column vector, an additional dimension
+ must be added, e.g., ``np.atleast_2d(a).T`` achieves this, as does
+ ``a[:, np.newaxis]``.
+ For a 2-D array, this is the standard matrix transpose.
+ For an n-D array, if axes are given, their order indicates how the
+ axes are permuted (see Examples). If axes are not provided, then
+ ``transpose(a).shape == a.shape[::-1]``.
+
+ Parameters
+ ----------
+ a : array_like
+ Input array.
+ axes : tuple or list of ints, optional
+ If specified, it must be a tuple or list which contains a permutation
+ of [0, 1, ..., N-1] where N is the number of axes of `a`. Negative
+ indices can also be used to specify axes. The i-th axis of the returned
+ array will correspond to the axis numbered ``axes[i]`` of the input.
+ If not specified, defaults to ``range(a.ndim)[::-1]``, which reverses
+ the order of the axes.
+
+ Returns
+ -------
+ p : ndarray
+ `a` with its axes permuted. A view is returned whenever possible.
+
+ See Also
+ --------
+ ndarray.transpose : Equivalent method.
+ moveaxis : Move axes of an array to new positions.
+ argsort : Return the indices that would sort an array.
+
+ Notes
+ -----
+ Use ``transpose(a, argsort(axes))`` to invert the transposition of tensors
+ when using the `axes` keyword argument.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[1, 2], [3, 4]])
+ >>> a
+ array([[1, 2],
+ [3, 4]])
+ >>> np.transpose(a)
+ array([[1, 3],
+ [2, 4]])
+
+ >>> a = np.array([1, 2, 3, 4])
+ >>> a
+ array([1, 2, 3, 4])
+ >>> np.transpose(a)
+ array([1, 2, 3, 4])
+
+ >>> a = np.ones((1, 2, 3))
+ >>> np.transpose(a, (1, 0, 2)).shape
+ (2, 1, 3)
+
+ >>> a = np.ones((2, 3, 4, 5))
+ >>> np.transpose(a).shape
+ (5, 4, 3, 2)
+
+ >>> a = np.arange(3*4*5).reshape((3, 4, 5))
+ >>> np.transpose(a, (-1, 0, -2)).shape
+ (5, 3, 4)
+
+ """
+ return _wrapfunc(a, 'transpose', axes)
+
+
+def _matrix_transpose_dispatcher(x):
+ return (x,)
+
+@array_function_dispatch(_matrix_transpose_dispatcher)
+def matrix_transpose(x, /):
+ """
+ Transposes a matrix (or a stack of matrices) ``x``.
+
+ This function is Array API compatible.
+
+ Parameters
+ ----------
+ x : array_like
+ Input array having shape (..., M, N) and whose two innermost
+ dimensions form ``MxN`` matrices.
+
+ Returns
+ -------
+ out : ndarray
+ An array containing the transpose for each matrix and having shape
+ (..., N, M).
+
+ See Also
+ --------
+ transpose : Generic transpose method.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.matrix_transpose([[1, 2], [3, 4]])
+ array([[1, 3],
+ [2, 4]])
+
+ >>> np.matrix_transpose([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
+ array([[[1, 3],
+ [2, 4]],
+ [[5, 7],
+ [6, 8]]])
+
+ """
+ x = asanyarray(x)
+ if x.ndim < 2:
+ raise ValueError(
+ f"Input array must be at least 2-dimensional, but it is {x.ndim}"
+ )
+ return swapaxes(x, -1, -2)
+
+
+def _partition_dispatcher(a, kth, axis=None, kind=None, order=None):
+ return (a,)
+
+
+@array_function_dispatch(_partition_dispatcher)
+def partition(a, kth, axis=-1, kind='introselect', order=None):
+ """
+ Return a partitioned copy of an array.
+
+ Creates a copy of the array and partially sorts it in such a way that
+ the value of the element in k-th position is in the position it would be
+ in a sorted array. In the output array, all elements smaller than the k-th
+ element are located to the left of this element and all equal or greater
+ are located to its right. The ordering of the elements in the two
+ partitions on the either side of the k-th element in the output array is
+ undefined.
+
+ Parameters
+ ----------
+ a : array_like
+ Array to be sorted.
+ kth : int or sequence of ints
+ Element index to partition by. The k-th value of the element
+ will be in its final sorted position and all smaller elements
+ will be moved before it and all equal or greater elements behind
+ it. The order of all elements in the partitions is undefined. If
+ provided with a sequence of k-th it will partition all elements
+ indexed by k-th of them into their sorted position at once.
+
+ .. deprecated:: 1.22.0
+ Passing booleans as index is deprecated.
+ axis : int or None, optional
+ Axis along which to sort. If None, the array is flattened before
+ sorting. The default is -1, which sorts along the last axis.
+ kind : {'introselect'}, optional
+ Selection algorithm. Default is 'introselect'.
+ order : str or list of str, optional
+ When `a` is an array with fields defined, this argument
+ specifies which fields to compare first, second, etc. A single
+ field can be specified as a string. Not all fields need be
+ specified, but unspecified fields will still be used, in the
+ order in which they come up in the dtype, to break ties.
+
+ Returns
+ -------
+ partitioned_array : ndarray
+ Array of the same type and shape as `a`.
+
+ See Also
+ --------
+ ndarray.partition : Method to sort an array in-place.
+ argpartition : Indirect partition.
+ sort : Full sorting
+
+ Notes
+ -----
+ The various selection algorithms are characterized by their average
+ speed, worst case performance, work space size, and whether they are
+ stable. A stable sort keeps items with the same key in the same
+ relative order. The available algorithms have the following
+ properties:
+
+ ================= ======= ============= ============ =======
+ kind speed worst case work space stable
+ ================= ======= ============= ============ =======
+ 'introselect' 1 O(n) 0 no
+ ================= ======= ============= ============ =======
+
+ All the partition algorithms make temporary copies of the data when
+ partitioning along any but the last axis. Consequently,
+ partitioning along the last axis is faster and uses less space than
+ partitioning along any other axis.
+
+ The sort order for complex numbers is lexicographic. If both the
+ real and imaginary parts are non-nan then the order is determined by
+ the real parts except when they are equal, in which case the order
+ is determined by the imaginary parts.
+
+ The sort order of ``np.nan`` is bigger than ``np.inf``.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([7, 1, 7, 7, 1, 5, 7, 2, 3, 2, 6, 2, 3, 0])
+ >>> p = np.partition(a, 4)
+ >>> p
+ array([0, 1, 2, 1, 2, 5, 2, 3, 3, 6, 7, 7, 7, 7]) # may vary
+
+ ``p[4]`` is 2; all elements in ``p[:4]`` are less than or equal
+ to ``p[4]``, and all elements in ``p[5:]`` are greater than or
+ equal to ``p[4]``. The partition is::
+
+ [0, 1, 2, 1], [2], [5, 2, 3, 3, 6, 7, 7, 7, 7]
+
+ The next example shows the use of multiple values passed to `kth`.
+
+ >>> p2 = np.partition(a, (4, 8))
+ >>> p2
+ array([0, 1, 2, 1, 2, 3, 3, 2, 5, 6, 7, 7, 7, 7])
+
+ ``p2[4]`` is 2 and ``p2[8]`` is 5. All elements in ``p2[:4]``
+ are less than or equal to ``p2[4]``, all elements in ``p2[5:8]``
+ are greater than or equal to ``p2[4]`` and less than or equal to
+ ``p2[8]``, and all elements in ``p2[9:]`` are greater than or
+ equal to ``p2[8]``. The partition is::
+
+ [0, 1, 2, 1], [2], [3, 3, 2], [5], [6, 7, 7, 7, 7]
+ """
+ if axis is None:
+ # flatten returns (1, N) for np.matrix, so always use the last axis
+ a = asanyarray(a).flatten()
+ axis = -1
+ else:
+ a = asanyarray(a).copy(order="K")
+ a.partition(kth, axis=axis, kind=kind, order=order)
+ return a
+
+
+def _argpartition_dispatcher(a, kth, axis=None, kind=None, order=None):
+ return (a,)
+
+
+@array_function_dispatch(_argpartition_dispatcher)
+def argpartition(a, kth, axis=-1, kind='introselect', order=None):
+ """
+ Perform an indirect partition along the given axis using the
+ algorithm specified by the `kind` keyword. It returns an array of
+ indices of the same shape as `a` that index data along the given
+ axis in partitioned order.
+
+ Parameters
+ ----------
+ a : array_like
+ Array to sort.
+ kth : int or sequence of ints
+ Element index to partition by. The k-th element will be in its
+ final sorted position and all smaller elements will be moved
+ before it and all larger elements behind it. The order of all
+ elements in the partitions is undefined. If provided with a
+ sequence of k-th it will partition all of them into their sorted
+ position at once.
+
+ .. deprecated:: 1.22.0
+ Passing booleans as index is deprecated.
+ axis : int or None, optional
+ Axis along which to sort. The default is -1 (the last axis). If
+ None, the flattened array is used.
+ kind : {'introselect'}, optional
+ Selection algorithm. Default is 'introselect'
+ order : str or list of str, optional
+ When `a` is an array with fields defined, this argument
+ specifies which fields to compare first, second, etc. A single
+ field can be specified as a string, and not all fields need be
+ specified, but unspecified fields will still be used, in the
+ order in which they come up in the dtype, to break ties.
+
+ Returns
+ -------
+ index_array : ndarray, int
+ Array of indices that partition `a` along the specified axis.
+ If `a` is one-dimensional, ``a[index_array]`` yields a partitioned `a`.
+ More generally, ``np.take_along_axis(a, index_array, axis=axis)``
+ always yields the partitioned `a`, irrespective of dimensionality.
+
+ See Also
+ --------
+ partition : Describes partition algorithms used.
+ ndarray.partition : Inplace partition.
+ argsort : Full indirect sort.
+ take_along_axis : Apply ``index_array`` from argpartition
+ to an array as if by calling partition.
+
+ Notes
+ -----
+ The returned indices are not guaranteed to be sorted according to
+ the values. Furthermore, the default selection algorithm ``introselect``
+ is unstable, and hence the returned indices are not guaranteed
+ to be the earliest/latest occurrence of the element.
+
+ `argpartition` works for real/complex inputs with nan values,
+ see `partition` for notes on the enhanced sort order and
+ different selection algorithms.
+
+ Examples
+ --------
+ One dimensional array:
+
+ >>> import numpy as np
+ >>> x = np.array([3, 4, 2, 1])
+ >>> x[np.argpartition(x, 3)]
+ array([2, 1, 3, 4]) # may vary
+ >>> x[np.argpartition(x, (1, 3))]
+ array([1, 2, 3, 4]) # may vary
+
+ >>> x = [3, 4, 2, 1]
+ >>> np.array(x)[np.argpartition(x, 3)]
+ array([2, 1, 3, 4]) # may vary
+
+ Multi-dimensional array:
+
+ >>> x = np.array([[3, 4, 2], [1, 3, 1]])
+ >>> index_array = np.argpartition(x, kth=1, axis=-1)
+ >>> # below is the same as np.partition(x, kth=1)
+ >>> np.take_along_axis(x, index_array, axis=-1)
+ array([[2, 3, 4],
+ [1, 1, 3]])
+
+ """
+ return _wrapfunc(a, 'argpartition', kth, axis=axis, kind=kind, order=order)
+
+
+def _sort_dispatcher(a, axis=None, kind=None, order=None, *, stable=None):
+ return (a,)
+
+
+@array_function_dispatch(_sort_dispatcher)
+def sort(a, axis=-1, kind=None, order=None, *, stable=None):
+ """
+ Return a sorted copy of an array.
+
+ Parameters
+ ----------
+ a : array_like
+ Array to be sorted.
+ axis : int or None, optional
+ Axis along which to sort. If None, the array is flattened before
+ sorting. The default is -1, which sorts along the last axis.
+ kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
+ Sorting algorithm. The default is 'quicksort'. Note that both 'stable'
+ and 'mergesort' use timsort or radix sort under the covers and,
+ in general, the actual implementation will vary with data type.
+ The 'mergesort' option is retained for backwards compatibility.
+ order : str or list of str, optional
+ When `a` is an array with fields defined, this argument specifies
+ which fields to compare first, second, etc. A single field can
+ be specified as a string, and not all fields need be specified,
+ but unspecified fields will still be used, in the order in which
+ they come up in the dtype, to break ties.
+ stable : bool, optional
+ Sort stability. If ``True``, the returned array will maintain
+ the relative order of ``a`` values which compare as equal.
+ If ``False`` or ``None``, this is not guaranteed. Internally,
+ this option selects ``kind='stable'``. Default: ``None``.
+
+ .. versionadded:: 2.0.0
+
+ Returns
+ -------
+ sorted_array : ndarray
+ Array of the same type and shape as `a`.
+
+ See Also
+ --------
+ ndarray.sort : Method to sort an array in-place.
+ argsort : Indirect sort.
+ lexsort : Indirect stable sort on multiple keys.
+ searchsorted : Find elements in a sorted array.
+ partition : Partial sort.
+
+ Notes
+ -----
+ The various sorting algorithms are characterized by their average speed,
+ worst case performance, work space size, and whether they are stable. A
+ stable sort keeps items with the same key in the same relative
+ order. The four algorithms implemented in NumPy have the following
+ properties:
+
+ =========== ======= ============= ============ ========
+ kind speed worst case work space stable
+ =========== ======= ============= ============ ========
+ 'quicksort' 1 O(n^2) 0 no
+ 'heapsort' 3 O(n*log(n)) 0 no
+ 'mergesort' 2 O(n*log(n)) ~n/2 yes
+ 'timsort' 2 O(n*log(n)) ~n/2 yes
+ =========== ======= ============= ============ ========
+
+ .. note:: The datatype determines which of 'mergesort' or 'timsort'
+ is actually used, even if 'mergesort' is specified. User selection
+ at a finer scale is not currently available.
+
+ For performance, ``sort`` makes a temporary copy if needed to make the data
+ `contiguous `_
+ in memory along the sort axis. For even better performance and reduced
+ memory consumption, ensure that the array is already contiguous along the
+ sort axis.
+
+ The sort order for complex numbers is lexicographic. If both the real
+ and imaginary parts are non-nan then the order is determined by the
+ real parts except when they are equal, in which case the order is
+ determined by the imaginary parts.
+
+ Previous to numpy 1.4.0 sorting real and complex arrays containing nan
+ values led to undefined behaviour. In numpy versions >= 1.4.0 nan
+ values are sorted to the end. The extended sort order is:
+
+ * Real: [R, nan]
+ * Complex: [R + Rj, R + nanj, nan + Rj, nan + nanj]
+
+ where R is a non-nan real value. Complex values with the same nan
+ placements are sorted according to the non-nan part if it exists.
+ Non-nan values are sorted as before.
+
+ quicksort has been changed to:
+ `introsort `_.
+ When sorting does not make enough progress it switches to
+ `heapsort `_.
+ This implementation makes quicksort O(n*log(n)) in the worst case.
+
+ 'stable' automatically chooses the best stable sorting algorithm
+ for the data type being sorted.
+ It, along with 'mergesort' is currently mapped to
+ `timsort `_
+ or `radix sort `_
+ depending on the data type.
+ API forward compatibility currently limits the
+ ability to select the implementation and it is hardwired for the different
+ data types.
+
+ Timsort is added for better performance on already or nearly
+ sorted data. On random data timsort is almost identical to
+ mergesort. It is now used for stable sort while quicksort is still the
+ default sort if none is chosen. For timsort details, refer to
+ `CPython listsort.txt
+ `_
+ 'mergesort' and 'stable' are mapped to radix sort for integer data types.
+ Radix sort is an O(n) sort instead of O(n log n).
+
+ NaT now sorts to the end of arrays for consistency with NaN.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[1,4],[3,1]])
+ >>> np.sort(a) # sort along the last axis
+ array([[1, 4],
+ [1, 3]])
+ >>> np.sort(a, axis=None) # sort the flattened array
+ array([1, 1, 3, 4])
+ >>> np.sort(a, axis=0) # sort along the first axis
+ array([[1, 1],
+ [3, 4]])
+
+ Use the `order` keyword to specify a field to use when sorting a
+ structured array:
+
+ >>> dtype = [('name', 'S10'), ('height', float), ('age', int)]
+ >>> values = [('Arthur', 1.8, 41), ('Lancelot', 1.9, 38),
+ ... ('Galahad', 1.7, 38)]
+ >>> a = np.array(values, dtype=dtype) # create a structured array
+ >>> np.sort(a, order='height') # doctest: +SKIP
+ array([('Galahad', 1.7, 38), ('Arthur', 1.8, 41),
+ ('Lancelot', 1.8999999999999999, 38)],
+ dtype=[('name', '|S10'), ('height', '>> np.sort(a, order=['age', 'height']) # doctest: +SKIP
+ array([('Galahad', 1.7, 38), ('Lancelot', 1.8999999999999999, 38),
+ ('Arthur', 1.8, 41)],
+ dtype=[('name', '|S10'), ('height', '>> import numpy as np
+ >>> x = np.array([3, 1, 2])
+ >>> np.argsort(x)
+ array([1, 2, 0])
+
+ Two-dimensional array:
+
+ >>> x = np.array([[0, 3], [2, 2]])
+ >>> x
+ array([[0, 3],
+ [2, 2]])
+
+ >>> ind = np.argsort(x, axis=0) # sorts along first axis (down)
+ >>> ind
+ array([[0, 1],
+ [1, 0]])
+ >>> np.take_along_axis(x, ind, axis=0) # same as np.sort(x, axis=0)
+ array([[0, 2],
+ [2, 3]])
+
+ >>> ind = np.argsort(x, axis=1) # sorts along last axis (across)
+ >>> ind
+ array([[0, 1],
+ [0, 1]])
+ >>> np.take_along_axis(x, ind, axis=1) # same as np.sort(x, axis=1)
+ array([[0, 3],
+ [2, 2]])
+
+ Indices of the sorted elements of a N-dimensional array:
+
+ >>> ind = np.unravel_index(np.argsort(x, axis=None), x.shape)
+ >>> ind
+ (array([0, 1, 1, 0]), array([0, 0, 1, 1]))
+ >>> x[ind] # same as np.sort(x, axis=None)
+ array([0, 2, 2, 3])
+
+ Sorting with keys:
+
+ >>> x = np.array([(1, 0), (0, 1)], dtype=[('x', '>> x
+ array([(1, 0), (0, 1)],
+ dtype=[('x', '>> np.argsort(x, order=('x','y'))
+ array([1, 0])
+
+ >>> np.argsort(x, order=('y','x'))
+ array([0, 1])
+
+ """
+ return _wrapfunc(
+ a, 'argsort', axis=axis, kind=kind, order=order, stable=stable
+ )
+
+def _argmax_dispatcher(a, axis=None, out=None, *, keepdims=np._NoValue):
+ return (a, out)
+
+
+@array_function_dispatch(_argmax_dispatcher)
+def argmax(a, axis=None, out=None, *, keepdims=np._NoValue):
+ """
+ Returns the indices of the maximum values along an axis.
+
+ Parameters
+ ----------
+ a : array_like
+ Input array.
+ axis : int, optional
+ By default, the index is into the flattened array, otherwise
+ along the specified axis.
+ out : array, optional
+ If provided, the result will be inserted into this array. It should
+ be of the appropriate shape and dtype.
+ keepdims : bool, optional
+ If this is set to True, the axes which are reduced are left
+ in the result as dimensions with size one. With this option,
+ the result will broadcast correctly against the array.
+
+ .. versionadded:: 1.22.0
+
+ Returns
+ -------
+ index_array : ndarray of ints
+ Array of indices into the array. It has the same shape as ``a.shape``
+ with the dimension along `axis` removed. If `keepdims` is set to True,
+ then the size of `axis` will be 1 with the resulting array having same
+ shape as ``a.shape``.
+
+ See Also
+ --------
+ ndarray.argmax, argmin
+ amax : The maximum value along a given axis.
+ unravel_index : Convert a flat index into an index tuple.
+ take_along_axis : Apply ``np.expand_dims(index_array, axis)``
+ from argmax to an array as if by calling max.
+
+ Notes
+ -----
+ In case of multiple occurrences of the maximum values, the indices
+ corresponding to the first occurrence are returned.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.arange(6).reshape(2,3) + 10
+ >>> a
+ array([[10, 11, 12],
+ [13, 14, 15]])
+ >>> np.argmax(a)
+ 5
+ >>> np.argmax(a, axis=0)
+ array([1, 1, 1])
+ >>> np.argmax(a, axis=1)
+ array([2, 2])
+
+ Indexes of the maximal elements of a N-dimensional array:
+
+ >>> ind = np.unravel_index(np.argmax(a, axis=None), a.shape)
+ >>> ind
+ (1, 2)
+ >>> a[ind]
+ 15
+
+ >>> b = np.arange(6)
+ >>> b[1] = 5
+ >>> b
+ array([0, 5, 2, 3, 4, 5])
+ >>> np.argmax(b) # Only the first occurrence is returned.
+ 1
+
+ >>> x = np.array([[4,2,3], [1,0,3]])
+ >>> index_array = np.argmax(x, axis=-1)
+ >>> # Same as np.amax(x, axis=-1, keepdims=True)
+ >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1)
+ array([[4],
+ [3]])
+ >>> # Same as np.amax(x, axis=-1)
+ >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1),
+ ... axis=-1).squeeze(axis=-1)
+ array([4, 3])
+
+ Setting `keepdims` to `True`,
+
+ >>> x = np.arange(24).reshape((2, 3, 4))
+ >>> res = np.argmax(x, axis=1, keepdims=True)
+ >>> res.shape
+ (2, 1, 4)
+ """
+ kwds = {'keepdims': keepdims} if keepdims is not np._NoValue else {}
+ return _wrapfunc(a, 'argmax', axis=axis, out=out, **kwds)
+
+
+def _argmin_dispatcher(a, axis=None, out=None, *, keepdims=np._NoValue):
+ return (a, out)
+
+
+@array_function_dispatch(_argmin_dispatcher)
+def argmin(a, axis=None, out=None, *, keepdims=np._NoValue):
+ """
+ Returns the indices of the minimum values along an axis.
+
+ Parameters
+ ----------
+ a : array_like
+ Input array.
+ axis : int, optional
+ By default, the index is into the flattened array, otherwise
+ along the specified axis.
+ out : array, optional
+ If provided, the result will be inserted into this array. It should
+ be of the appropriate shape and dtype.
+ keepdims : bool, optional
+ If this is set to True, the axes which are reduced are left
+ in the result as dimensions with size one. With this option,
+ the result will broadcast correctly against the array.
+
+ .. versionadded:: 1.22.0
+
+ Returns
+ -------
+ index_array : ndarray of ints
+ Array of indices into the array. It has the same shape as `a.shape`
+ with the dimension along `axis` removed. If `keepdims` is set to True,
+ then the size of `axis` will be 1 with the resulting array having same
+ shape as `a.shape`.
+
+ See Also
+ --------
+ ndarray.argmin, argmax
+ amin : The minimum value along a given axis.
+ unravel_index : Convert a flat index into an index tuple.
+ take_along_axis : Apply ``np.expand_dims(index_array, axis)``
+ from argmin to an array as if by calling min.
+
+ Notes
+ -----
+ In case of multiple occurrences of the minimum values, the indices
+ corresponding to the first occurrence are returned.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.arange(6).reshape(2,3) + 10
+ >>> a
+ array([[10, 11, 12],
+ [13, 14, 15]])
+ >>> np.argmin(a)
+ 0
+ >>> np.argmin(a, axis=0)
+ array([0, 0, 0])
+ >>> np.argmin(a, axis=1)
+ array([0, 0])
+
+ Indices of the minimum elements of a N-dimensional array:
+
+ >>> ind = np.unravel_index(np.argmin(a, axis=None), a.shape)
+ >>> ind
+ (0, 0)
+ >>> a[ind]
+ 10
+
+ >>> b = np.arange(6) + 10
+ >>> b[4] = 10
+ >>> b
+ array([10, 11, 12, 13, 10, 15])
+ >>> np.argmin(b) # Only the first occurrence is returned.
+ 0
+
+ >>> x = np.array([[4,2,3], [1,0,3]])
+ >>> index_array = np.argmin(x, axis=-1)
+ >>> # Same as np.amin(x, axis=-1, keepdims=True)
+ >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1)
+ array([[2],
+ [0]])
+ >>> # Same as np.amax(x, axis=-1)
+ >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1),
+ ... axis=-1).squeeze(axis=-1)
+ array([2, 0])
+
+ Setting `keepdims` to `True`,
+
+ >>> x = np.arange(24).reshape((2, 3, 4))
+ >>> res = np.argmin(x, axis=1, keepdims=True)
+ >>> res.shape
+ (2, 1, 4)
+ """
+ kwds = {'keepdims': keepdims} if keepdims is not np._NoValue else {}
+ return _wrapfunc(a, 'argmin', axis=axis, out=out, **kwds)
+
+
+def _searchsorted_dispatcher(a, v, side=None, sorter=None):
+ return (a, v, sorter)
+
+
+@array_function_dispatch(_searchsorted_dispatcher)
+def searchsorted(a, v, side='left', sorter=None):
+ """
+ Find indices where elements should be inserted to maintain order.
+
+ Find the indices into a sorted array `a` such that, if the
+ corresponding elements in `v` were inserted before the indices, the
+ order of `a` would be preserved.
+
+ Assuming that `a` is sorted:
+
+ ====== ============================
+ `side` returned index `i` satisfies
+ ====== ============================
+ left ``a[i-1] < v <= a[i]``
+ right ``a[i-1] <= v < a[i]``
+ ====== ============================
+
+ Parameters
+ ----------
+ a : 1-D array_like
+ Input array. If `sorter` is None, then it must be sorted in
+ ascending order, otherwise `sorter` must be an array of indices
+ that sort it.
+ v : array_like
+ Values to insert into `a`.
+ side : {'left', 'right'}, optional
+ If 'left', the index of the first suitable location found is given.
+ If 'right', return the last such index. If there is no suitable
+ index, return either 0 or N (where N is the length of `a`).
+ sorter : 1-D array_like, optional
+ Optional array of integer indices that sort array a into ascending
+ order. They are typically the result of argsort.
+
+ Returns
+ -------
+ indices : int or array of ints
+ Array of insertion points with the same shape as `v`,
+ or an integer if `v` is a scalar.
+
+ See Also
+ --------
+ sort : Return a sorted copy of an array.
+ histogram : Produce histogram from 1-D data.
+
+ Notes
+ -----
+ Binary search is used to find the required insertion points.
+
+ As of NumPy 1.4.0 `searchsorted` works with real/complex arrays containing
+ `nan` values. The enhanced sort order is documented in `sort`.
+
+ This function uses the same algorithm as the builtin python
+ `bisect.bisect_left` (``side='left'``) and `bisect.bisect_right`
+ (``side='right'``) functions, which is also vectorized
+ in the `v` argument.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.searchsorted([11,12,13,14,15], 13)
+ 2
+ >>> np.searchsorted([11,12,13,14,15], 13, side='right')
+ 3
+ >>> np.searchsorted([11,12,13,14,15], [-10, 20, 12, 13])
+ array([0, 5, 1, 2])
+
+ When `sorter` is used, the returned indices refer to the sorted
+ array of `a` and not `a` itself:
+
+ >>> a = np.array([40, 10, 20, 30])
+ >>> sorter = np.argsort(a)
+ >>> sorter
+ array([1, 2, 3, 0]) # Indices that would sort the array 'a'
+ >>> result = np.searchsorted(a, 25, sorter=sorter)
+ >>> result
+ 2
+ >>> a[sorter[result]]
+ 30 # The element at index 2 of the sorted array is 30.
+ """
+ return _wrapfunc(a, 'searchsorted', v, side=side, sorter=sorter)
+
+
+def _resize_dispatcher(a, new_shape):
+ return (a,)
+
+
+@array_function_dispatch(_resize_dispatcher)
+def resize(a, new_shape):
+ """
+ Return a new array with the specified shape.
+
+ If the new array is larger than the original array, then the new
+ array is filled with repeated copies of `a`. Note that this behavior
+ is different from a.resize(new_shape) which fills with zeros instead
+ of repeated copies of `a`.
+
+ Parameters
+ ----------
+ a : array_like
+ Array to be resized.
+
+ new_shape : int or tuple of int
+ Shape of resized array.
+
+ Returns
+ -------
+ reshaped_array : ndarray
+ The new array is formed from the data in the old array, repeated
+ if necessary to fill out the required number of elements. The
+ data are repeated iterating over the array in C-order.
+
+ See Also
+ --------
+ numpy.reshape : Reshape an array without changing the total size.
+ numpy.pad : Enlarge and pad an array.
+ numpy.repeat : Repeat elements of an array.
+ ndarray.resize : resize an array in-place.
+
+ Notes
+ -----
+ When the total size of the array does not change `~numpy.reshape` should
+ be used. In most other cases either indexing (to reduce the size)
+ or padding (to increase the size) may be a more appropriate solution.
+
+ Warning: This functionality does **not** consider axes separately,
+ i.e. it does not apply interpolation/extrapolation.
+ It fills the return array with the required number of elements, iterating
+ over `a` in C-order, disregarding axes (and cycling back from the start if
+ the new shape is larger). This functionality is therefore not suitable to
+ resize images, or data where each axis represents a separate and distinct
+ entity.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[0,1],[2,3]])
+ >>> np.resize(a,(2,3))
+ array([[0, 1, 2],
+ [3, 0, 1]])
+ >>> np.resize(a,(1,4))
+ array([[0, 1, 2, 3]])
+ >>> np.resize(a,(2,4))
+ array([[0, 1, 2, 3],
+ [0, 1, 2, 3]])
+
+ """
+ if isinstance(new_shape, (int, nt.integer)):
+ new_shape = (new_shape,)
+
+ a = ravel(a)
+
+ new_size = 1
+ for dim_length in new_shape:
+ new_size *= dim_length
+ if dim_length < 0:
+ raise ValueError(
+ 'all elements of `new_shape` must be non-negative'
+ )
+
+ if a.size == 0 or new_size == 0:
+ # First case must zero fill. The second would have repeats == 0.
+ return np.zeros_like(a, shape=new_shape)
+
+ repeats = -(-new_size // a.size) # ceil division
+ a = concatenate((a,) * repeats)[:new_size]
+
+ return reshape(a, new_shape)
+
+
+def _squeeze_dispatcher(a, axis=None):
+ return (a,)
+
+
+@array_function_dispatch(_squeeze_dispatcher)
+def squeeze(a, axis=None):
+ """
+ Remove axes of length one from `a`.
+
+ Parameters
+ ----------
+ a : array_like
+ Input data.
+ axis : None or int or tuple of ints, optional
+ Selects a subset of the entries of length one in the
+ shape. If an axis is selected with shape entry greater than
+ one, an error is raised.
+
+ Returns
+ -------
+ squeezed : ndarray
+ The input array, but with all or a subset of the
+ dimensions of length 1 removed. This is always `a` itself
+ or a view into `a`. Note that if all axes are squeezed,
+ the result is a 0d array and not a scalar.
+
+ Raises
+ ------
+ ValueError
+ If `axis` is not None, and an axis being squeezed is not of length 1
+
+ See Also
+ --------
+ expand_dims : The inverse operation, adding entries of length one
+ reshape : Insert, remove, and combine dimensions, and resize existing ones
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.array([[[0], [1], [2]]])
+ >>> x.shape
+ (1, 3, 1)
+ >>> np.squeeze(x).shape
+ (3,)
+ >>> np.squeeze(x, axis=0).shape
+ (3, 1)
+ >>> np.squeeze(x, axis=1).shape
+ Traceback (most recent call last):
+ ...
+ ValueError: cannot select an axis to squeeze out which has size
+ not equal to one
+ >>> np.squeeze(x, axis=2).shape
+ (1, 3)
+ >>> x = np.array([[1234]])
+ >>> x.shape
+ (1, 1)
+ >>> np.squeeze(x)
+ array(1234) # 0d array
+ >>> np.squeeze(x).shape
+ ()
+ >>> np.squeeze(x)[()]
+ 1234
+
+ """
+ try:
+ squeeze = a.squeeze
+ except AttributeError:
+ return _wrapit(a, 'squeeze', axis=axis)
+ if axis is None:
+ return squeeze()
+ else:
+ return squeeze(axis=axis)
+
+
+def _diagonal_dispatcher(a, offset=None, axis1=None, axis2=None):
+ return (a,)
+
+
+@array_function_dispatch(_diagonal_dispatcher)
+def diagonal(a, offset=0, axis1=0, axis2=1):
+ """
+ Return specified diagonals.
+
+ If `a` is 2-D, returns the diagonal of `a` with the given offset,
+ i.e., the collection of elements of the form ``a[i, i+offset]``. If
+ `a` has more than two dimensions, then the axes specified by `axis1`
+ and `axis2` are used to determine the 2-D sub-array whose diagonal is
+ returned. The shape of the resulting array can be determined by
+ removing `axis1` and `axis2` and appending an index to the right equal
+ to the size of the resulting diagonals.
+
+ In versions of NumPy prior to 1.7, this function always returned a new,
+ independent array containing a copy of the values in the diagonal.
+
+ In NumPy 1.7 and 1.8, it continues to return a copy of the diagonal,
+ but depending on this fact is deprecated. Writing to the resulting
+ array continues to work as it used to, but a FutureWarning is issued.
+
+ Starting in NumPy 1.9 it returns a read-only view on the original array.
+ Attempting to write to the resulting array will produce an error.
+
+ In some future release, it will return a read/write view and writing to
+ the returned array will alter your original array. The returned array
+ will have the same type as the input array.
+
+ If you don't write to the array returned by this function, then you can
+ just ignore all of the above.
+
+ If you depend on the current behavior, then we suggest copying the
+ returned array explicitly, i.e., use ``np.diagonal(a).copy()`` instead
+ of just ``np.diagonal(a)``. This will work with both past and future
+ versions of NumPy.
+
+ Parameters
+ ----------
+ a : array_like
+ Array from which the diagonals are taken.
+ offset : int, optional
+ Offset of the diagonal from the main diagonal. Can be positive or
+ negative. Defaults to main diagonal (0).
+ axis1 : int, optional
+ Axis to be used as the first axis of the 2-D sub-arrays from which
+ the diagonals should be taken. Defaults to first axis (0).
+ axis2 : int, optional
+ Axis to be used as the second axis of the 2-D sub-arrays from
+ which the diagonals should be taken. Defaults to second axis (1).
+
+ Returns
+ -------
+ array_of_diagonals : ndarray
+ If `a` is 2-D, then a 1-D array containing the diagonal and of the
+ same type as `a` is returned unless `a` is a `matrix`, in which case
+ a 1-D array rather than a (2-D) `matrix` is returned in order to
+ maintain backward compatibility.
+
+ If ``a.ndim > 2``, then the dimensions specified by `axis1` and `axis2`
+ are removed, and a new axis inserted at the end corresponding to the
+ diagonal.
+
+ Raises
+ ------
+ ValueError
+ If the dimension of `a` is less than 2.
+
+ See Also
+ --------
+ diag : MATLAB work-a-like for 1-D and 2-D arrays.
+ diagflat : Create diagonal arrays.
+ trace : Sum along diagonals.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.arange(4).reshape(2,2)
+ >>> a
+ array([[0, 1],
+ [2, 3]])
+ >>> a.diagonal()
+ array([0, 3])
+ >>> a.diagonal(1)
+ array([1])
+
+ A 3-D example:
+
+ >>> a = np.arange(8).reshape(2,2,2); a
+ array([[[0, 1],
+ [2, 3]],
+ [[4, 5],
+ [6, 7]]])
+ >>> a.diagonal(0, # Main diagonals of two arrays created by skipping
+ ... 0, # across the outer(left)-most axis last and
+ ... 1) # the "middle" (row) axis first.
+ array([[0, 6],
+ [1, 7]])
+
+ The sub-arrays whose main diagonals we just obtained; note that each
+ corresponds to fixing the right-most (column) axis, and that the
+ diagonals are "packed" in rows.
+
+ >>> a[:,:,0] # main diagonal is [0 6]
+ array([[0, 2],
+ [4, 6]])
+ >>> a[:,:,1] # main diagonal is [1 7]
+ array([[1, 3],
+ [5, 7]])
+
+ The anti-diagonal can be obtained by reversing the order of elements
+ using either `numpy.flipud` or `numpy.fliplr`.
+
+ >>> a = np.arange(9).reshape(3, 3)
+ >>> a
+ array([[0, 1, 2],
+ [3, 4, 5],
+ [6, 7, 8]])
+ >>> np.fliplr(a).diagonal() # Horizontal flip
+ array([2, 4, 6])
+ >>> np.flipud(a).diagonal() # Vertical flip
+ array([6, 4, 2])
+
+ Note that the order in which the diagonal is retrieved varies depending
+ on the flip function.
+ """
+ if isinstance(a, np.matrix):
+ # Make diagonal of matrix 1-D to preserve backward compatibility.
+ return asarray(a).diagonal(offset=offset, axis1=axis1, axis2=axis2)
+ else:
+ return asanyarray(a).diagonal(offset=offset, axis1=axis1, axis2=axis2)
+
+
+def _trace_dispatcher(
+ a, offset=None, axis1=None, axis2=None, dtype=None, out=None):
+ return (a, out)
+
+
+@array_function_dispatch(_trace_dispatcher)
+def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None):
+ """
+ Return the sum along diagonals of the array.
+
+ If `a` is 2-D, the sum along its diagonal with the given offset
+ is returned, i.e., the sum of elements ``a[i,i+offset]`` for all i.
+
+ If `a` has more than two dimensions, then the axes specified by axis1 and
+ axis2 are used to determine the 2-D sub-arrays whose traces are returned.
+ The shape of the resulting array is the same as that of `a` with `axis1`
+ and `axis2` removed.
+
+ Parameters
+ ----------
+ a : array_like
+ Input array, from which the diagonals are taken.
+ offset : int, optional
+ Offset of the diagonal from the main diagonal. Can be both positive
+ and negative. Defaults to 0.
+ axis1, axis2 : int, optional
+ Axes to be used as the first and second axis of the 2-D sub-arrays
+ from which the diagonals should be taken. Defaults are the first two
+ axes of `a`.
+ dtype : dtype, optional
+ Determines the data-type of the returned array and of the accumulator
+ where the elements are summed. If dtype has the value None and `a` is
+ of integer type of precision less than the default integer
+ precision, then the default integer precision is used. Otherwise,
+ the precision is the same as that of `a`.
+ out : ndarray, optional
+ Array into which the output is placed. Its type is preserved and
+ it must be of the right shape to hold the output.
+
+ Returns
+ -------
+ sum_along_diagonals : ndarray
+ If `a` is 2-D, the sum along the diagonal is returned. If `a` has
+ larger dimensions, then an array of sums along diagonals is returned.
+
+ See Also
+ --------
+ diag, diagonal, diagflat
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.trace(np.eye(3))
+ 3.0
+ >>> a = np.arange(8).reshape((2,2,2))
+ >>> np.trace(a)
+ array([6, 8])
+
+ >>> a = np.arange(24).reshape((2,2,2,3))
+ >>> np.trace(a).shape
+ (2, 3)
+
+ """
+ if isinstance(a, np.matrix):
+ # Get trace of matrix via an array to preserve backward compatibility.
+ return asarray(a).trace(
+ offset=offset, axis1=axis1, axis2=axis2, dtype=dtype, out=out
+ )
+ else:
+ return asanyarray(a).trace(
+ offset=offset, axis1=axis1, axis2=axis2, dtype=dtype, out=out
+ )
+
+
+def _ravel_dispatcher(a, order=None):
+ return (a,)
+
+
+@array_function_dispatch(_ravel_dispatcher)
+def ravel(a, order='C'):
+ """Return a contiguous flattened array.
+
+ A 1-D array, containing the elements of the input, is returned. A copy is
+ made only if needed.
+
+ As of NumPy 1.10, the returned array will have the same type as the input
+ array. (for example, a masked array will be returned for a masked array
+ input)
+
+ Parameters
+ ----------
+ a : array_like
+ Input array. The elements in `a` are read in the order specified by
+ `order`, and packed as a 1-D array.
+ order : {'C','F', 'A', 'K'}, optional
+
+ The elements of `a` are read using this index order. 'C' means
+ to index the elements in row-major, C-style order,
+ with the last axis index changing fastest, back to the first
+ axis index changing slowest. 'F' means to index the elements
+ in column-major, Fortran-style order, with the
+ first index changing fastest, and the last index changing
+ slowest. Note that the 'C' and 'F' options take no account of
+ the memory layout of the underlying array, and only refer to
+ the order of axis indexing. 'A' means to read the elements in
+ Fortran-like index order if `a` is Fortran *contiguous* in
+ memory, C-like order otherwise. 'K' means to read the
+ elements in the order they occur in memory, except for
+ reversing the data when strides are negative. By default, 'C'
+ index order is used.
+
+ Returns
+ -------
+ y : array_like
+ y is a contiguous 1-D array of the same subtype as `a`,
+ with shape ``(a.size,)``.
+ Note that matrices are special cased for backward compatibility,
+ if `a` is a matrix, then y is a 1-D ndarray.
+
+ See Also
+ --------
+ ndarray.flat : 1-D iterator over an array.
+ ndarray.flatten : 1-D array copy of the elements of an array
+ in row-major order.
+ ndarray.reshape : Change the shape of an array without changing its data.
+
+ Notes
+ -----
+ In row-major, C-style order, in two dimensions, the row index
+ varies the slowest, and the column index the quickest. This can
+ be generalized to multiple dimensions, where row-major order
+ implies that the index along the first axis varies slowest, and
+ the index along the last quickest. The opposite holds for
+ column-major, Fortran-style index ordering.
+
+ When a view is desired in as many cases as possible, ``arr.reshape(-1)``
+ may be preferable. However, ``ravel`` supports ``K`` in the optional
+ ``order`` argument while ``reshape`` does not.
+
+ Examples
+ --------
+ It is equivalent to ``reshape(-1, order=order)``.
+
+ >>> import numpy as np
+ >>> x = np.array([[1, 2, 3], [4, 5, 6]])
+ >>> np.ravel(x)
+ array([1, 2, 3, 4, 5, 6])
+
+ >>> x.reshape(-1)
+ array([1, 2, 3, 4, 5, 6])
+
+ >>> np.ravel(x, order='F')
+ array([1, 4, 2, 5, 3, 6])
+
+ When ``order`` is 'A', it will preserve the array's 'C' or 'F' ordering:
+
+ >>> np.ravel(x.T)
+ array([1, 4, 2, 5, 3, 6])
+ >>> np.ravel(x.T, order='A')
+ array([1, 2, 3, 4, 5, 6])
+
+ When ``order`` is 'K', it will preserve orderings that are neither 'C'
+ nor 'F', but won't reverse axes:
+
+ >>> a = np.arange(3)[::-1]; a
+ array([2, 1, 0])
+ >>> a.ravel(order='C')
+ array([2, 1, 0])
+ >>> a.ravel(order='K')
+ array([2, 1, 0])
+
+ >>> a = np.arange(12).reshape(2,3,2).swapaxes(1,2); a
+ array([[[ 0, 2, 4],
+ [ 1, 3, 5]],
+ [[ 6, 8, 10],
+ [ 7, 9, 11]]])
+ >>> a.ravel(order='C')
+ array([ 0, 2, 4, 1, 3, 5, 6, 8, 10, 7, 9, 11])
+ >>> a.ravel(order='K')
+ array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
+
+ """
+ if isinstance(a, np.matrix):
+ return asarray(a).ravel(order=order)
+ else:
+ return asanyarray(a).ravel(order=order)
+
+
+def _nonzero_dispatcher(a):
+ return (a,)
+
+
+@array_function_dispatch(_nonzero_dispatcher)
+def nonzero(a):
+ """
+ Return the indices of the elements that are non-zero.
+
+ Returns a tuple of arrays, one for each dimension of `a`,
+ containing the indices of the non-zero elements in that
+ dimension. The values in `a` are always tested and returned in
+ row-major, C-style order.
+
+ To group the indices by element, rather than dimension, use `argwhere`,
+ which returns a row for each non-zero element.
+
+ .. note::
+
+ When called on a zero-d array or scalar, ``nonzero(a)`` is treated
+ as ``nonzero(atleast_1d(a))``.
+
+ .. deprecated:: 1.17.0
+
+ Use `atleast_1d` explicitly if this behavior is deliberate.
+
+ Parameters
+ ----------
+ a : array_like
+ Input array.
+
+ Returns
+ -------
+ tuple_of_arrays : tuple
+ Indices of elements that are non-zero.
+
+ See Also
+ --------
+ flatnonzero :
+ Return indices that are non-zero in the flattened version of the input
+ array.
+ ndarray.nonzero :
+ Equivalent ndarray method.
+ count_nonzero :
+ Counts the number of non-zero elements in the input array.
+
+ Notes
+ -----
+ While the nonzero values can be obtained with ``a[nonzero(a)]``, it is
+ recommended to use ``x[x.astype(bool)]`` or ``x[x != 0]`` instead, which
+ will correctly handle 0-d arrays.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.array([[3, 0, 0], [0, 4, 0], [5, 6, 0]])
+ >>> x
+ array([[3, 0, 0],
+ [0, 4, 0],
+ [5, 6, 0]])
+ >>> np.nonzero(x)
+ (array([0, 1, 2, 2]), array([0, 1, 0, 1]))
+
+ >>> x[np.nonzero(x)]
+ array([3, 4, 5, 6])
+ >>> np.transpose(np.nonzero(x))
+ array([[0, 0],
+ [1, 1],
+ [2, 0],
+ [2, 1]])
+
+ A common use for ``nonzero`` is to find the indices of an array, where
+ a condition is True. Given an array `a`, the condition `a` > 3 is a
+ boolean array and since False is interpreted as 0, np.nonzero(a > 3)
+ yields the indices of the `a` where the condition is true.
+
+ >>> a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
+ >>> a > 3
+ array([[False, False, False],
+ [ True, True, True],
+ [ True, True, True]])
+ >>> np.nonzero(a > 3)
+ (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
+
+ Using this result to index `a` is equivalent to using the mask directly:
+
+ >>> a[np.nonzero(a > 3)]
+ array([4, 5, 6, 7, 8, 9])
+ >>> a[a > 3] # prefer this spelling
+ array([4, 5, 6, 7, 8, 9])
+
+ ``nonzero`` can also be called as a method of the array.
+
+ >>> (a > 3).nonzero()
+ (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
+
+ """
+ return _wrapfunc(a, 'nonzero')
+
+
+def _shape_dispatcher(a):
+ return (a,)
+
+
+@array_function_dispatch(_shape_dispatcher)
+def shape(a):
+ """
+ Return the shape of an array.
+
+ Parameters
+ ----------
+ a : array_like
+ Input array.
+
+ Returns
+ -------
+ shape : tuple of ints
+ The elements of the shape tuple give the lengths of the
+ corresponding array dimensions.
+
+ See Also
+ --------
+ len : ``len(a)`` is equivalent to ``np.shape(a)[0]`` for N-D arrays with
+ ``N>=1``.
+ ndarray.shape : Equivalent array method.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.shape(np.eye(3))
+ (3, 3)
+ >>> np.shape([[1, 3]])
+ (1, 2)
+ >>> np.shape([0])
+ (1,)
+ >>> np.shape(0)
+ ()
+
+ >>> a = np.array([(1, 2), (3, 4), (5, 6)],
+ ... dtype=[('x', 'i4'), ('y', 'i4')])
+ >>> np.shape(a)
+ (3,)
+ >>> a.shape
+ (3,)
+
+ """
+ try:
+ result = a.shape
+ except AttributeError:
+ result = asarray(a).shape
+ return result
+
+
+def _compress_dispatcher(condition, a, axis=None, out=None):
+ return (condition, a, out)
+
+
+@array_function_dispatch(_compress_dispatcher)
+def compress(condition, a, axis=None, out=None):
+ """
+ Return selected slices of an array along given axis.
+
+ When working along a given axis, a slice along that axis is returned in
+ `output` for each index where `condition` evaluates to True. When
+ working on a 1-D array, `compress` is equivalent to `extract`.
+
+ Parameters
+ ----------
+ condition : 1-D array of bools
+ Array that selects which entries to return. If len(condition)
+ is less than the size of `a` along the given axis, then output is
+ truncated to the length of the condition array.
+ a : array_like
+ Array from which to extract a part.
+ axis : int, optional
+ Axis along which to take slices. If None (default), work on the
+ flattened array.
+ out : ndarray, optional
+ Output array. Its type is preserved and it must be of the right
+ shape to hold the output.
+
+ Returns
+ -------
+ compressed_array : ndarray
+ A copy of `a` without the slices along axis for which `condition`
+ is false.
+
+ See Also
+ --------
+ take, choose, diag, diagonal, select
+ ndarray.compress : Equivalent method in ndarray
+ extract : Equivalent method when working on 1-D arrays
+ :ref:`ufuncs-output-type`
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[1, 2], [3, 4], [5, 6]])
+ >>> a
+ array([[1, 2],
+ [3, 4],
+ [5, 6]])
+ >>> np.compress([0, 1], a, axis=0)
+ array([[3, 4]])
+ >>> np.compress([False, True, True], a, axis=0)
+ array([[3, 4],
+ [5, 6]])
+ >>> np.compress([False, True], a, axis=1)
+ array([[2],
+ [4],
+ [6]])
+
+ Working on the flattened array does not return slices along an axis but
+ selects elements.
+
+ >>> np.compress([False, True], a)
+ array([2])
+
+ """
+ return _wrapfunc(a, 'compress', condition, axis=axis, out=out)
+
+
+def _clip_dispatcher(a, a_min=None, a_max=None, out=None, *, min=None,
+ max=None, **kwargs):
+ return (a, a_min, a_max, out, min, max)
+
+
+@array_function_dispatch(_clip_dispatcher)
+def clip(a, a_min=np._NoValue, a_max=np._NoValue, out=None, *,
+ min=np._NoValue, max=np._NoValue, **kwargs):
+ """
+ Clip (limit) the values in an array.
+
+ Given an interval, values outside the interval are clipped to
+ the interval edges. For example, if an interval of ``[0, 1]``
+ is specified, values smaller than 0 become 0, and values larger
+ than 1 become 1.
+
+ Equivalent to but faster than ``np.minimum(a_max, np.maximum(a, a_min))``.
+
+ No check is performed to ensure ``a_min < a_max``.
+
+ Parameters
+ ----------
+ a : array_like
+ Array containing elements to clip.
+ a_min, a_max : array_like or None
+ Minimum and maximum value. If ``None``, clipping is not performed on
+ the corresponding edge. If both ``a_min`` and ``a_max`` are ``None``,
+ the elements of the returned array stay the same. Both are broadcasted
+ against ``a``.
+ out : ndarray, optional
+ The results will be placed in this array. It may be the input
+ array for in-place clipping. `out` must be of the right shape
+ to hold the output. Its type is preserved.
+ min, max : array_like or None
+ Array API compatible alternatives for ``a_min`` and ``a_max``
+ arguments. Either ``a_min`` and ``a_max`` or ``min`` and ``max``
+ can be passed at the same time. Default: ``None``.
+
+ .. versionadded:: 2.1.0
+ **kwargs
+ For other keyword-only arguments, see the
+ :ref:`ufunc docs `.
+
+ Returns
+ -------
+ clipped_array : ndarray
+ An array with the elements of `a`, but where values
+ < `a_min` are replaced with `a_min`, and those > `a_max`
+ with `a_max`.
+
+ See Also
+ --------
+ :ref:`ufuncs-output-type`
+
+ Notes
+ -----
+ When `a_min` is greater than `a_max`, `clip` returns an
+ array in which all values are equal to `a_max`,
+ as shown in the second example.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.arange(10)
+ >>> a
+ array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
+ >>> np.clip(a, 1, 8)
+ array([1, 1, 2, 3, 4, 5, 6, 7, 8, 8])
+ >>> np.clip(a, 8, 1)
+ array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
+ >>> np.clip(a, 3, 6, out=a)
+ array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6])
+ >>> a
+ array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6])
+ >>> a = np.arange(10)
+ >>> a
+ array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
+ >>> np.clip(a, [3, 4, 1, 1, 1, 4, 4, 4, 4, 4], 8)
+ array([3, 4, 2, 3, 4, 5, 6, 7, 8, 8])
+
+ """
+ if a_min is np._NoValue and a_max is np._NoValue:
+ a_min = None if min is np._NoValue else min
+ a_max = None if max is np._NoValue else max
+ elif a_min is np._NoValue:
+ raise TypeError("clip() missing 1 required positional "
+ "argument: 'a_min'")
+ elif a_max is np._NoValue:
+ raise TypeError("clip() missing 1 required positional "
+ "argument: 'a_max'")
+ elif min is not np._NoValue or max is not np._NoValue:
+ raise ValueError("Passing `min` or `max` keyword argument when "
+ "`a_min` and `a_max` are provided is forbidden.")
+
+ return _wrapfunc(a, 'clip', a_min, a_max, out=out, **kwargs)
+
+
+def _sum_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None,
+ initial=None, where=None):
+ return (a, out)
+
+
+@array_function_dispatch(_sum_dispatcher)
+def sum(a, axis=None, dtype=None, out=None, keepdims=np._NoValue,
+ initial=np._NoValue, where=np._NoValue):
+ """
+ Sum of array elements over a given axis.
+
+ Parameters
+ ----------
+ a : array_like
+ Elements to sum.
+ axis : None or int or tuple of ints, optional
+ Axis or axes along which a sum is performed. The default,
+ axis=None, will sum all of the elements of the input array. If
+ axis is negative it counts from the last to the first axis. If
+ axis is a tuple of ints, a sum is performed on all of the axes
+ specified in the tuple instead of a single axis or all the axes as
+ before.
+ dtype : dtype, optional
+ The type of the returned array and of the accumulator in which the
+ elements are summed. The dtype of `a` is used by default unless `a`
+ has an integer dtype of less precision than the default platform
+ integer. In that case, if `a` is signed then the platform integer
+ is used while if `a` is unsigned then an unsigned integer of the
+ same precision as the platform integer is used.
+ out : ndarray, optional
+ Alternative output array in which to place the result. It must have
+ the same shape as the expected output, but the type of the output
+ values will be cast if necessary.
+ keepdims : bool, optional
+ If this is set to True, the axes which are reduced are left
+ in the result as dimensions with size one. With this option,
+ the result will broadcast correctly against the input array.
+
+ If the default value is passed, then `keepdims` will not be
+ passed through to the `sum` method of sub-classes of
+ `ndarray`, however any non-default value will be. If the
+ sub-class' method does not implement `keepdims` any
+ exceptions will be raised.
+ initial : scalar, optional
+ Starting value for the sum. See `~numpy.ufunc.reduce` for details.
+ where : array_like of bool, optional
+ Elements to include in the sum. See `~numpy.ufunc.reduce` for details.
+
+ Returns
+ -------
+ sum_along_axis : ndarray
+ An array with the same shape as `a`, with the specified
+ axis removed. If `a` is a 0-d array, or if `axis` is None, a scalar
+ is returned. If an output array is specified, a reference to
+ `out` is returned.
+
+ See Also
+ --------
+ ndarray.sum : Equivalent method.
+ add: ``numpy.add.reduce`` equivalent function.
+ cumsum : Cumulative sum of array elements.
+ trapezoid : Integration of array values using composite trapezoidal rule.
+
+ mean, average
+
+ Notes
+ -----
+ Arithmetic is modular when using integer types, and no error is
+ raised on overflow.
+
+ The sum of an empty array is the neutral element 0:
+
+ >>> np.sum([])
+ 0.0
+
+ For floating point numbers the numerical precision of sum (and
+ ``np.add.reduce``) is in general limited by directly adding each number
+ individually to the result causing rounding errors in every step.
+ However, often numpy will use a numerically better approach (partial
+ pairwise summation) leading to improved precision in many use-cases.
+ This improved precision is always provided when no ``axis`` is given.
+ When ``axis`` is given, it will depend on which axis is summed.
+ Technically, to provide the best speed possible, the improved precision
+ is only used when the summation is along the fast axis in memory.
+ Note that the exact precision may vary depending on other parameters.
+ In contrast to NumPy, Python's ``math.fsum`` function uses a slower but
+ more precise approach to summation.
+ Especially when summing a large number of lower precision floating point
+ numbers, such as ``float32``, numerical errors can become significant.
+ In such cases it can be advisable to use `dtype="float64"` to use a higher
+ precision for the output.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.sum([0.5, 1.5])
+ 2.0
+ >>> np.sum([0.5, 0.7, 0.2, 1.5], dtype=np.int32)
+ np.int32(1)
+ >>> np.sum([[0, 1], [0, 5]])
+ 6
+ >>> np.sum([[0, 1], [0, 5]], axis=0)
+ array([0, 6])
+ >>> np.sum([[0, 1], [0, 5]], axis=1)
+ array([1, 5])
+ >>> np.sum([[0, 1], [np.nan, 5]], where=[False, True], axis=1)
+ array([1., 5.])
+
+ If the accumulator is too small, overflow occurs:
+
+ >>> np.ones(128, dtype=np.int8).sum(dtype=np.int8)
+ np.int8(-128)
+
+ You can also start the sum with a value other than zero:
+
+ >>> np.sum([10], initial=5)
+ 15
+ """
+ if isinstance(a, _gentype):
+ # 2018-02-25, 1.15.0
+ warnings.warn(
+ "Calling np.sum(generator) is deprecated, and in the future will "
+ "give a different result. Use np.sum(np.fromiter(generator)) or "
+ "the python sum builtin instead.",
+ DeprecationWarning, stacklevel=2
+ )
+
+ res = _sum_(a)
+ if out is not None:
+ out[...] = res
+ return out
+ return res
+
+ return _wrapreduction(
+ a, np.add, 'sum', axis, dtype, out,
+ keepdims=keepdims, initial=initial, where=where
+ )
+
+
+def _any_dispatcher(a, axis=None, out=None, keepdims=None, *,
+ where=np._NoValue):
+ return (a, where, out)
+
+
+@array_function_dispatch(_any_dispatcher)
+def any(a, axis=None, out=None, keepdims=np._NoValue, *, where=np._NoValue):
+ """
+ Test whether any array element along a given axis evaluates to True.
+
+ Returns single boolean if `axis` is ``None``
+
+ Parameters
+ ----------
+ a : array_like
+ Input array or object that can be converted to an array.
+ axis : None or int or tuple of ints, optional
+ Axis or axes along which a logical OR reduction is performed.
+ The default (``axis=None``) is to perform a logical OR over all
+ the dimensions of the input array. `axis` may be negative, in
+ which case it counts from the last to the first axis. If this
+ is a tuple of ints, a reduction is performed on multiple
+ axes, instead of a single axis or all the axes as before.
+ out : ndarray, optional
+ Alternate output array in which to place the result. It must have
+ the same shape as the expected output and its type is preserved
+ (e.g., if it is of type float, then it will remain so, returning
+ 1.0 for True and 0.0 for False, regardless of the type of `a`).
+ See :ref:`ufuncs-output-type` for more details.
+
+ keepdims : bool, optional
+ If this is set to True, the axes which are reduced are left
+ in the result as dimensions with size one. With this option,
+ the result will broadcast correctly against the input array.
+
+ If the default value is passed, then `keepdims` will not be
+ passed through to the `any` method of sub-classes of
+ `ndarray`, however any non-default value will be. If the
+ sub-class' method does not implement `keepdims` any
+ exceptions will be raised.
+
+ where : array_like of bool, optional
+ Elements to include in checking for any `True` values.
+ See `~numpy.ufunc.reduce` for details.
+
+ .. versionadded:: 1.20.0
+
+ Returns
+ -------
+ any : bool or ndarray
+ A new boolean or `ndarray` is returned unless `out` is specified,
+ in which case a reference to `out` is returned.
+
+ See Also
+ --------
+ ndarray.any : equivalent method
+
+ all : Test whether all elements along a given axis evaluate to True.
+
+ Notes
+ -----
+ Not a Number (NaN), positive infinity and negative infinity evaluate
+ to `True` because these are not equal to zero.
+
+ .. versionchanged:: 2.0
+ Before NumPy 2.0, ``any`` did not return booleans for object dtype
+ input arrays.
+ This behavior is still available via ``np.logical_or.reduce``.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.any([[True, False], [True, True]])
+ True
+
+ >>> np.any([[True, False, True ],
+ ... [False, False, False]], axis=0)
+ array([ True, False, True])
+
+ >>> np.any([-1, 0, 5])
+ True
+
+ >>> np.any([[np.nan], [np.inf]], axis=1, keepdims=True)
+ array([[ True],
+ [ True]])
+
+ >>> np.any([[True, False], [False, False]], where=[[False], [True]])
+ False
+
+ >>> a = np.array([[1, 0, 0],
+ ... [0, 0, 1],
+ ... [0, 0, 0]])
+ >>> np.any(a, axis=0)
+ array([ True, False, True])
+ >>> np.any(a, axis=1)
+ array([ True, True, False])
+
+ >>> o=np.array(False)
+ >>> z=np.any([-1, 4, 5], out=o)
+ >>> z, o
+ (array(True), array(True))
+ >>> # Check now that z is a reference to o
+ >>> z is o
+ True
+ >>> id(z), id(o) # identity of z and o # doctest: +SKIP
+ (191614240, 191614240)
+
+ """
+ return _wrapreduction_any_all(a, np.logical_or, 'any', axis, out,
+ keepdims=keepdims, where=where)
+
+
+def _all_dispatcher(a, axis=None, out=None, keepdims=None, *,
+ where=None):
+ return (a, where, out)
+
+
+@array_function_dispatch(_all_dispatcher)
+def all(a, axis=None, out=None, keepdims=np._NoValue, *, where=np._NoValue):
+ """
+ Test whether all array elements along a given axis evaluate to True.
+
+ Parameters
+ ----------
+ a : array_like
+ Input array or object that can be converted to an array.
+ axis : None or int or tuple of ints, optional
+ Axis or axes along which a logical AND reduction is performed.
+ The default (``axis=None``) is to perform a logical AND over all
+ the dimensions of the input array. `axis` may be negative, in
+ which case it counts from the last to the first axis. If this
+ is a tuple of ints, a reduction is performed on multiple
+ axes, instead of a single axis or all the axes as before.
+ out : ndarray, optional
+ Alternate output array in which to place the result.
+ It must have the same shape as the expected output and its
+ type is preserved (e.g., if ``dtype(out)`` is float, the result
+ will consist of 0.0's and 1.0's). See :ref:`ufuncs-output-type`
+ for more details.
+
+ keepdims : bool, optional
+ If this is set to True, the axes which are reduced are left
+ in the result as dimensions with size one. With this option,
+ the result will broadcast correctly against the input array.
+
+ If the default value is passed, then `keepdims` will not be
+ passed through to the `all` method of sub-classes of
+ `ndarray`, however any non-default value will be. If the
+ sub-class' method does not implement `keepdims` any
+ exceptions will be raised.
+
+ where : array_like of bool, optional
+ Elements to include in checking for all `True` values.
+ See `~numpy.ufunc.reduce` for details.
+
+ .. versionadded:: 1.20.0
+
+ Returns
+ -------
+ all : ndarray, bool
+ A new boolean or array is returned unless `out` is specified,
+ in which case a reference to `out` is returned.
+
+ See Also
+ --------
+ ndarray.all : equivalent method
+
+ any : Test whether any element along a given axis evaluates to True.
+
+ Notes
+ -----
+ Not a Number (NaN), positive infinity and negative infinity
+ evaluate to `True` because these are not equal to zero.
+
+ .. versionchanged:: 2.0
+ Before NumPy 2.0, ``all`` did not return booleans for object dtype
+ input arrays.
+ This behavior is still available via ``np.logical_and.reduce``.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.all([[True,False],[True,True]])
+ False
+
+ >>> np.all([[True,False],[True,True]], axis=0)
+ array([ True, False])
+
+ >>> np.all([-1, 4, 5])
+ True
+
+ >>> np.all([1.0, np.nan])
+ True
+
+ >>> np.all([[True, True], [False, True]], where=[[True], [False]])
+ True
+
+ >>> o=np.array(False)
+ >>> z=np.all([-1, 4, 5], out=o)
+ >>> id(z), id(o), z
+ (28293632, 28293632, array(True)) # may vary
+
+ """
+ return _wrapreduction_any_all(a, np.logical_and, 'all', axis, out,
+ keepdims=keepdims, where=where)
+
+
+def _cumulative_func(x, func, axis, dtype, out, include_initial):
+ x = np.atleast_1d(x)
+ x_ndim = x.ndim
+ if axis is None:
+ if x_ndim >= 2:
+ raise ValueError("For arrays which have more than one dimension "
+ "``axis`` argument is required.")
+ axis = 0
+
+ if out is not None and include_initial:
+ item = [slice(None)] * x_ndim
+ item[axis] = slice(1, None)
+ func.accumulate(x, axis=axis, dtype=dtype, out=out[tuple(item)])
+ item[axis] = 0
+ out[tuple(item)] = func.identity
+ return out
+
+ res = func.accumulate(x, axis=axis, dtype=dtype, out=out)
+ if include_initial:
+ initial_shape = list(x.shape)
+ initial_shape[axis] = 1
+ res = np.concat(
+ [np.full_like(res, func.identity, shape=initial_shape), res],
+ axis=axis,
+ )
+
+ return res
+
+
+def _cumulative_prod_dispatcher(x, /, *, axis=None, dtype=None, out=None,
+ include_initial=None):
+ return (x, out)
+
+
+@array_function_dispatch(_cumulative_prod_dispatcher)
+def cumulative_prod(x, /, *, axis=None, dtype=None, out=None,
+ include_initial=False):
+ """
+ Return the cumulative product of elements along a given axis.
+
+ This function is an Array API compatible alternative to `numpy.cumprod`.
+
+ Parameters
+ ----------
+ x : array_like
+ Input array.
+ axis : int, optional
+ Axis along which the cumulative product is computed. The default
+ (None) is only allowed for one-dimensional arrays. For arrays
+ with more than one dimension ``axis`` is required.
+ dtype : dtype, optional
+ Type of the returned array, as well as of the accumulator in which
+ the elements are multiplied. If ``dtype`` is not specified, it
+ defaults to the dtype of ``x``, unless ``x`` has an integer dtype
+ with a precision less than that of the default platform integer.
+ In that case, the default platform integer is used instead.
+ out : ndarray, optional
+ Alternative output array in which to place the result. It must
+ have the same shape and buffer length as the expected output
+ but the type of the resulting values will be cast if necessary.
+ See :ref:`ufuncs-output-type` for more details.
+ include_initial : bool, optional
+ Boolean indicating whether to include the initial value (ones) as
+ the first value in the output. With ``include_initial=True``
+ the shape of the output is different than the shape of the input.
+ Default: ``False``.
+
+ Returns
+ -------
+ cumulative_prod_along_axis : ndarray
+ A new array holding the result is returned unless ``out`` is
+ specified, in which case a reference to ``out`` is returned. The
+ result has the same shape as ``x`` if ``include_initial=False``.
+
+ Notes
+ -----
+ Arithmetic is modular when using integer types, and no error is
+ raised on overflow.
+
+ Examples
+ --------
+ >>> a = np.array([1, 2, 3])
+ >>> np.cumulative_prod(a) # intermediate results 1, 1*2
+ ... # total product 1*2*3 = 6
+ array([1, 2, 6])
+ >>> a = np.array([1, 2, 3, 4, 5, 6])
+ >>> np.cumulative_prod(a, dtype=float) # specify type of output
+ array([ 1., 2., 6., 24., 120., 720.])
+
+ The cumulative product for each column (i.e., over the rows) of ``b``:
+
+ >>> b = np.array([[1, 2, 3], [4, 5, 6]])
+ >>> np.cumulative_prod(b, axis=0)
+ array([[ 1, 2, 3],
+ [ 4, 10, 18]])
+
+ The cumulative product for each row (i.e. over the columns) of ``b``:
+
+ >>> np.cumulative_prod(b, axis=1)
+ array([[ 1, 2, 6],
+ [ 4, 20, 120]])
+
+ """
+ return _cumulative_func(x, um.multiply, axis, dtype, out, include_initial)
+
+
+def _cumulative_sum_dispatcher(x, /, *, axis=None, dtype=None, out=None,
+ include_initial=None):
+ return (x, out)
+
+
+@array_function_dispatch(_cumulative_sum_dispatcher)
+def cumulative_sum(x, /, *, axis=None, dtype=None, out=None,
+ include_initial=False):
+ """
+ Return the cumulative sum of the elements along a given axis.
+
+ This function is an Array API compatible alternative to `numpy.cumsum`.
+
+ Parameters
+ ----------
+ x : array_like
+ Input array.
+ axis : int, optional
+ Axis along which the cumulative sum is computed. The default
+ (None) is only allowed for one-dimensional arrays. For arrays
+ with more than one dimension ``axis`` is required.
+ dtype : dtype, optional
+ Type of the returned array and of the accumulator in which the
+ elements are summed. If ``dtype`` is not specified, it defaults
+ to the dtype of ``x``, unless ``x`` has an integer dtype with
+ a precision less than that of the default platform integer.
+ In that case, the default platform integer is used.
+ out : ndarray, optional
+ Alternative output array in which to place the result. It must
+ have the same shape and buffer length as the expected output
+ but the type will be cast if necessary. See :ref:`ufuncs-output-type`
+ for more details.
+ include_initial : bool, optional
+ Boolean indicating whether to include the initial value (zeros) as
+ the first value in the output. With ``include_initial=True``
+ the shape of the output is different than the shape of the input.
+ Default: ``False``.
+
+ Returns
+ -------
+ cumulative_sum_along_axis : ndarray
+ A new array holding the result is returned unless ``out`` is
+ specified, in which case a reference to ``out`` is returned. The
+ result has the same shape as ``x`` if ``include_initial=False``.
+
+ See Also
+ --------
+ sum : Sum array elements.
+ trapezoid : Integration of array values using composite trapezoidal rule.
+ diff : Calculate the n-th discrete difference along given axis.
+
+ Notes
+ -----
+ Arithmetic is modular when using integer types, and no error is
+ raised on overflow.
+
+ ``cumulative_sum(a)[-1]`` may not be equal to ``sum(a)`` for
+ floating-point values since ``sum`` may use a pairwise summation routine,
+ reducing the roundoff-error. See `sum` for more information.
+
+ Examples
+ --------
+ >>> a = np.array([1, 2, 3, 4, 5, 6])
+ >>> a
+ array([1, 2, 3, 4, 5, 6])
+ >>> np.cumulative_sum(a)
+ array([ 1, 3, 6, 10, 15, 21])
+ >>> np.cumulative_sum(a, dtype=float) # specifies type of output value(s)
+ array([ 1., 3., 6., 10., 15., 21.])
+
+ >>> b = np.array([[1, 2, 3], [4, 5, 6]])
+ >>> np.cumulative_sum(b,axis=0) # sum over rows for each of the 3 columns
+ array([[1, 2, 3],
+ [5, 7, 9]])
+ >>> np.cumulative_sum(b,axis=1) # sum over columns for each of the 2 rows
+ array([[ 1, 3, 6],
+ [ 4, 9, 15]])
+
+ ``cumulative_sum(c)[-1]`` may not be equal to ``sum(c)``
+
+ >>> c = np.array([1, 2e-9, 3e-9] * 1000000)
+ >>> np.cumulative_sum(c)[-1]
+ 1000000.0050045159
+ >>> c.sum()
+ 1000000.0050000029
+
+ """
+ return _cumulative_func(x, um.add, axis, dtype, out, include_initial)
+
+
+def _cumsum_dispatcher(a, axis=None, dtype=None, out=None):
+ return (a, out)
+
+
+@array_function_dispatch(_cumsum_dispatcher)
+def cumsum(a, axis=None, dtype=None, out=None):
+ """
+ Return the cumulative sum of the elements along a given axis.
+
+ Parameters
+ ----------
+ a : array_like
+ Input array.
+ axis : int, optional
+ Axis along which the cumulative sum is computed. The default
+ (None) is to compute the cumsum over the flattened array.
+ dtype : dtype, optional
+ Type of the returned array and of the accumulator in which the
+ elements are summed. If `dtype` is not specified, it defaults
+ to the dtype of `a`, unless `a` has an integer dtype with a
+ precision less than that of the default platform integer. In
+ that case, the default platform integer is used.
+ out : ndarray, optional
+ Alternative output array in which to place the result. It must
+ have the same shape and buffer length as the expected output
+ but the type will be cast if necessary. See :ref:`ufuncs-output-type`
+ for more details.
+
+ Returns
+ -------
+ cumsum_along_axis : ndarray.
+ A new array holding the result is returned unless `out` is
+ specified, in which case a reference to `out` is returned. The
+ result has the same size as `a`, and the same shape as `a` if
+ `axis` is not None or `a` is a 1-d array.
+
+ See Also
+ --------
+ cumulative_sum : Array API compatible alternative for ``cumsum``.
+ sum : Sum array elements.
+ trapezoid : Integration of array values using composite trapezoidal rule.
+ diff : Calculate the n-th discrete difference along given axis.
+
+ Notes
+ -----
+ Arithmetic is modular when using integer types, and no error is
+ raised on overflow.
+
+ ``cumsum(a)[-1]`` may not be equal to ``sum(a)`` for floating-point
+ values since ``sum`` may use a pairwise summation routine, reducing
+ the roundoff-error. See `sum` for more information.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[1,2,3], [4,5,6]])
+ >>> a
+ array([[1, 2, 3],
+ [4, 5, 6]])
+ >>> np.cumsum(a)
+ array([ 1, 3, 6, 10, 15, 21])
+ >>> np.cumsum(a, dtype=float) # specifies type of output value(s)
+ array([ 1., 3., 6., 10., 15., 21.])
+
+ >>> np.cumsum(a,axis=0) # sum over rows for each of the 3 columns
+ array([[1, 2, 3],
+ [5, 7, 9]])
+ >>> np.cumsum(a,axis=1) # sum over columns for each of the 2 rows
+ array([[ 1, 3, 6],
+ [ 4, 9, 15]])
+
+ ``cumsum(b)[-1]`` may not be equal to ``sum(b)``
+
+ >>> b = np.array([1, 2e-9, 3e-9] * 1000000)
+ >>> b.cumsum()[-1]
+ 1000000.0050045159
+ >>> b.sum()
+ 1000000.0050000029
+
+ """
+ return _wrapfunc(a, 'cumsum', axis=axis, dtype=dtype, out=out)
+
+
+def _ptp_dispatcher(a, axis=None, out=None, keepdims=None):
+ return (a, out)
+
+
+@array_function_dispatch(_ptp_dispatcher)
+def ptp(a, axis=None, out=None, keepdims=np._NoValue):
+ """
+ Range of values (maximum - minimum) along an axis.
+
+ The name of the function comes from the acronym for 'peak to peak'.
+
+ .. warning::
+ `ptp` preserves the data type of the array. This means the
+ return value for an input of signed integers with n bits
+ (e.g. `numpy.int8`, `numpy.int16`, etc) is also a signed integer
+ with n bits. In that case, peak-to-peak values greater than
+ ``2**(n-1)-1`` will be returned as negative values. An example
+ with a work-around is shown below.
+
+ Parameters
+ ----------
+ a : array_like
+ Input values.
+ axis : None or int or tuple of ints, optional
+ Axis along which to find the peaks. By default, flatten the
+ array. `axis` may be negative, in
+ which case it counts from the last to the first axis.
+ If this is a tuple of ints, a reduction is performed on multiple
+ axes, instead of a single axis or all the axes as before.
+ out : array_like
+ Alternative output array in which to place the result. It must
+ have the same shape and buffer length as the expected output,
+ but the type of the output values will be cast if necessary.
+
+ keepdims : bool, optional
+ If this is set to True, the axes which are reduced are left
+ in the result as dimensions with size one. With this option,
+ the result will broadcast correctly against the input array.
+
+ If the default value is passed, then `keepdims` will not be
+ passed through to the `ptp` method of sub-classes of
+ `ndarray`, however any non-default value will be. If the
+ sub-class' method does not implement `keepdims` any
+ exceptions will be raised.
+
+ Returns
+ -------
+ ptp : ndarray or scalar
+ The range of a given array - `scalar` if array is one-dimensional
+ or a new array holding the result along the given axis
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.array([[4, 9, 2, 10],
+ ... [6, 9, 7, 12]])
+
+ >>> np.ptp(x, axis=1)
+ array([8, 6])
+
+ >>> np.ptp(x, axis=0)
+ array([2, 0, 5, 2])
+
+ >>> np.ptp(x)
+ 10
+
+ This example shows that a negative value can be returned when
+ the input is an array of signed integers.
+
+ >>> y = np.array([[1, 127],
+ ... [0, 127],
+ ... [-1, 127],
+ ... [-2, 127]], dtype=np.int8)
+ >>> np.ptp(y, axis=1)
+ array([ 126, 127, -128, -127], dtype=int8)
+
+ A work-around is to use the `view()` method to view the result as
+ unsigned integers with the same bit width:
+
+ >>> np.ptp(y, axis=1).view(np.uint8)
+ array([126, 127, 128, 129], dtype=uint8)
+
+ """
+ kwargs = {}
+ if keepdims is not np._NoValue:
+ kwargs['keepdims'] = keepdims
+ return _methods._ptp(a, axis=axis, out=out, **kwargs)
+
+
+def _max_dispatcher(a, axis=None, out=None, keepdims=None, initial=None,
+ where=None):
+ return (a, out)
+
+
+@array_function_dispatch(_max_dispatcher)
+@set_module('numpy')
+def max(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue,
+ where=np._NoValue):
+ """
+ Return the maximum of an array or maximum along an axis.
+
+ Parameters
+ ----------
+ a : array_like
+ Input data.
+ axis : None or int or tuple of ints, optional
+ Axis or axes along which to operate. By default, flattened input is
+ used. If this is a tuple of ints, the maximum is selected over
+ multiple axes, instead of a single axis or all the axes as before.
+
+ out : ndarray, optional
+ Alternative output array in which to place the result. Must
+ be of the same shape and buffer length as the expected output.
+ See :ref:`ufuncs-output-type` for more details.
+
+ keepdims : bool, optional
+ If this is set to True, the axes which are reduced are left
+ in the result as dimensions with size one. With this option,
+ the result will broadcast correctly against the input array.
+
+ If the default value is passed, then `keepdims` will not be
+ passed through to the ``max`` method of sub-classes of
+ `ndarray`, however any non-default value will be. If the
+ sub-class' method does not implement `keepdims` any
+ exceptions will be raised.
+
+ initial : scalar, optional
+ The minimum value of an output element. Must be present to allow
+ computation on empty slice. See `~numpy.ufunc.reduce` for details.
+
+ where : array_like of bool, optional
+ Elements to compare for the maximum. See `~numpy.ufunc.reduce`
+ for details.
+
+ Returns
+ -------
+ max : ndarray or scalar
+ Maximum of `a`. If `axis` is None, the result is a scalar value.
+ If `axis` is an int, the result is an array of dimension
+ ``a.ndim - 1``. If `axis` is a tuple, the result is an array of
+ dimension ``a.ndim - len(axis)``.
+
+ See Also
+ --------
+ amin :
+ The minimum value of an array along a given axis, propagating any NaNs.
+ nanmax :
+ The maximum value of an array along a given axis, ignoring any NaNs.
+ maximum :
+ Element-wise maximum of two arrays, propagating any NaNs.
+ fmax :
+ Element-wise maximum of two arrays, ignoring any NaNs.
+ argmax :
+ Return the indices of the maximum values.
+
+ nanmin, minimum, fmin
+
+ Notes
+ -----
+ NaN values are propagated, that is if at least one item is NaN, the
+ corresponding max value will be NaN as well. To ignore NaN values
+ (MATLAB behavior), please use nanmax.
+
+ Don't use `~numpy.max` for element-wise comparison of 2 arrays; when
+ ``a.shape[0]`` is 2, ``maximum(a[0], a[1])`` is faster than
+ ``max(a, axis=0)``.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.arange(4).reshape((2,2))
+ >>> a
+ array([[0, 1],
+ [2, 3]])
+ >>> np.max(a) # Maximum of the flattened array
+ 3
+ >>> np.max(a, axis=0) # Maxima along the first axis
+ array([2, 3])
+ >>> np.max(a, axis=1) # Maxima along the second axis
+ array([1, 3])
+ >>> np.max(a, where=[False, True], initial=-1, axis=0)
+ array([-1, 3])
+ >>> b = np.arange(5, dtype=float)
+ >>> b[2] = np.nan
+ >>> np.max(b)
+ np.float64(nan)
+ >>> np.max(b, where=~np.isnan(b), initial=-1)
+ 4.0
+ >>> np.nanmax(b)
+ 4.0
+
+ You can use an initial value to compute the maximum of an empty slice, or
+ to initialize it to a different value:
+
+ >>> np.max([[-50], [10]], axis=-1, initial=0)
+ array([ 0, 10])
+
+ Notice that the initial value is used as one of the elements for which the
+ maximum is determined, unlike for the default argument Python's max
+ function, which is only used for empty iterables.
+
+ >>> np.max([5], initial=6)
+ 6
+ >>> max([5], default=6)
+ 5
+ """
+ return _wrapreduction(a, np.maximum, 'max', axis, None, out,
+ keepdims=keepdims, initial=initial, where=where)
+
+
+@array_function_dispatch(_max_dispatcher)
+def amax(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue,
+ where=np._NoValue):
+ """
+ Return the maximum of an array or maximum along an axis.
+
+ `amax` is an alias of `~numpy.max`.
+
+ See Also
+ --------
+ max : alias of this function
+ ndarray.max : equivalent method
+ """
+ return _wrapreduction(a, np.maximum, 'max', axis, None, out,
+ keepdims=keepdims, initial=initial, where=where)
+
+
+def _min_dispatcher(a, axis=None, out=None, keepdims=None, initial=None,
+ where=None):
+ return (a, out)
+
+
+@array_function_dispatch(_min_dispatcher)
+def min(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue,
+ where=np._NoValue):
+ """
+ Return the minimum of an array or minimum along an axis.
+
+ Parameters
+ ----------
+ a : array_like
+ Input data.
+ axis : None or int or tuple of ints, optional
+ Axis or axes along which to operate. By default, flattened input is
+ used.
+
+ If this is a tuple of ints, the minimum is selected over multiple axes,
+ instead of a single axis or all the axes as before.
+ out : ndarray, optional
+ Alternative output array in which to place the result. Must
+ be of the same shape and buffer length as the expected output.
+ See :ref:`ufuncs-output-type` for more details.
+
+ keepdims : bool, optional
+ If this is set to True, the axes which are reduced are left
+ in the result as dimensions with size one. With this option,
+ the result will broadcast correctly against the input array.
+
+ If the default value is passed, then `keepdims` will not be
+ passed through to the ``min`` method of sub-classes of
+ `ndarray`, however any non-default value will be. If the
+ sub-class' method does not implement `keepdims` any
+ exceptions will be raised.
+
+ initial : scalar, optional
+ The maximum value of an output element. Must be present to allow
+ computation on empty slice. See `~numpy.ufunc.reduce` for details.
+
+ where : array_like of bool, optional
+ Elements to compare for the minimum. See `~numpy.ufunc.reduce`
+ for details.
+
+ Returns
+ -------
+ min : ndarray or scalar
+ Minimum of `a`. If `axis` is None, the result is a scalar value.
+ If `axis` is an int, the result is an array of dimension
+ ``a.ndim - 1``. If `axis` is a tuple, the result is an array of
+ dimension ``a.ndim - len(axis)``.
+
+ See Also
+ --------
+ amax :
+ The maximum value of an array along a given axis, propagating any NaNs.
+ nanmin :
+ The minimum value of an array along a given axis, ignoring any NaNs.
+ minimum :
+ Element-wise minimum of two arrays, propagating any NaNs.
+ fmin :
+ Element-wise minimum of two arrays, ignoring any NaNs.
+ argmin :
+ Return the indices of the minimum values.
+
+ nanmax, maximum, fmax
+
+ Notes
+ -----
+ NaN values are propagated, that is if at least one item is NaN, the
+ corresponding min value will be NaN as well. To ignore NaN values
+ (MATLAB behavior), please use nanmin.
+
+ Don't use `~numpy.min` for element-wise comparison of 2 arrays; when
+ ``a.shape[0]`` is 2, ``minimum(a[0], a[1])`` is faster than
+ ``min(a, axis=0)``.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.arange(4).reshape((2,2))
+ >>> a
+ array([[0, 1],
+ [2, 3]])
+ >>> np.min(a) # Minimum of the flattened array
+ 0
+ >>> np.min(a, axis=0) # Minima along the first axis
+ array([0, 1])
+ >>> np.min(a, axis=1) # Minima along the second axis
+ array([0, 2])
+ >>> np.min(a, where=[False, True], initial=10, axis=0)
+ array([10, 1])
+
+ >>> b = np.arange(5, dtype=float)
+ >>> b[2] = np.nan
+ >>> np.min(b)
+ np.float64(nan)
+ >>> np.min(b, where=~np.isnan(b), initial=10)
+ 0.0
+ >>> np.nanmin(b)
+ 0.0
+
+ >>> np.min([[-50], [10]], axis=-1, initial=0)
+ array([-50, 0])
+
+ Notice that the initial value is used as one of the elements for which the
+ minimum is determined, unlike for the default argument Python's max
+ function, which is only used for empty iterables.
+
+ Notice that this isn't the same as Python's ``default`` argument.
+
+ >>> np.min([6], initial=5)
+ 5
+ >>> min([6], default=5)
+ 6
+ """
+ return _wrapreduction(a, np.minimum, 'min', axis, None, out,
+ keepdims=keepdims, initial=initial, where=where)
+
+
+@array_function_dispatch(_min_dispatcher)
+def amin(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue,
+ where=np._NoValue):
+ """
+ Return the minimum of an array or minimum along an axis.
+
+ `amin` is an alias of `~numpy.min`.
+
+ See Also
+ --------
+ min : alias of this function
+ ndarray.min : equivalent method
+ """
+ return _wrapreduction(a, np.minimum, 'min', axis, None, out,
+ keepdims=keepdims, initial=initial, where=where)
+
+
+def _prod_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None,
+ initial=None, where=None):
+ return (a, out)
+
+
+@array_function_dispatch(_prod_dispatcher)
+def prod(a, axis=None, dtype=None, out=None, keepdims=np._NoValue,
+ initial=np._NoValue, where=np._NoValue):
+ """
+ Return the product of array elements over a given axis.
+
+ Parameters
+ ----------
+ a : array_like
+ Input data.
+ axis : None or int or tuple of ints, optional
+ Axis or axes along which a product is performed. The default,
+ axis=None, will calculate the product of all the elements in the
+ input array. If axis is negative it counts from the last to the
+ first axis.
+
+ If axis is a tuple of ints, a product is performed on all of the
+ axes specified in the tuple instead of a single axis or all the
+ axes as before.
+ dtype : dtype, optional
+ The type of the returned array, as well as of the accumulator in
+ which the elements are multiplied. The dtype of `a` is used by
+ default unless `a` has an integer dtype of less precision than the
+ default platform integer. In that case, if `a` is signed then the
+ platform integer is used while if `a` is unsigned then an unsigned
+ integer of the same precision as the platform integer is used.
+ out : ndarray, optional
+ Alternative output array in which to place the result. It must have
+ the same shape as the expected output, but the type of the output
+ values will be cast if necessary.
+ keepdims : bool, optional
+ If this is set to True, the axes which are reduced are left in the
+ result as dimensions with size one. With this option, the result
+ will broadcast correctly against the input array.
+
+ If the default value is passed, then `keepdims` will not be
+ passed through to the `prod` method of sub-classes of
+ `ndarray`, however any non-default value will be. If the
+ sub-class' method does not implement `keepdims` any
+ exceptions will be raised.
+ initial : scalar, optional
+ The starting value for this product. See `~numpy.ufunc.reduce`
+ for details.
+ where : array_like of bool, optional
+ Elements to include in the product. See `~numpy.ufunc.reduce`
+ for details.
+
+ Returns
+ -------
+ product_along_axis : ndarray, see `dtype` parameter above.
+ An array shaped as `a` but with the specified axis removed.
+ Returns a reference to `out` if specified.
+
+ See Also
+ --------
+ ndarray.prod : equivalent method
+ :ref:`ufuncs-output-type`
+
+ Notes
+ -----
+ Arithmetic is modular when using integer types, and no error is
+ raised on overflow. That means that, on a 32-bit platform:
+
+ >>> x = np.array([536870910, 536870910, 536870910, 536870910])
+ >>> np.prod(x)
+ 16 # may vary
+
+ The product of an empty array is the neutral element 1:
+
+ >>> np.prod([])
+ 1.0
+
+ Examples
+ --------
+ By default, calculate the product of all elements:
+
+ >>> import numpy as np
+ >>> np.prod([1.,2.])
+ 2.0
+
+ Even when the input array is two-dimensional:
+
+ >>> a = np.array([[1., 2.], [3., 4.]])
+ >>> np.prod(a)
+ 24.0
+
+ But we can also specify the axis over which to multiply:
+
+ >>> np.prod(a, axis=1)
+ array([ 2., 12.])
+ >>> np.prod(a, axis=0)
+ array([3., 8.])
+
+ Or select specific elements to include:
+
+ >>> np.prod([1., np.nan, 3.], where=[True, False, True])
+ 3.0
+
+ If the type of `x` is unsigned, then the output type is
+ the unsigned platform integer:
+
+ >>> x = np.array([1, 2, 3], dtype=np.uint8)
+ >>> np.prod(x).dtype == np.uint
+ True
+
+ If `x` is of a signed integer type, then the output type
+ is the default platform integer:
+
+ >>> x = np.array([1, 2, 3], dtype=np.int8)
+ >>> np.prod(x).dtype == int
+ True
+
+ You can also start the product with a value other than one:
+
+ >>> np.prod([1, 2], initial=5)
+ 10
+ """
+ return _wrapreduction(a, np.multiply, 'prod', axis, dtype, out,
+ keepdims=keepdims, initial=initial, where=where)
+
+
+def _cumprod_dispatcher(a, axis=None, dtype=None, out=None):
+ return (a, out)
+
+
+@array_function_dispatch(_cumprod_dispatcher)
+def cumprod(a, axis=None, dtype=None, out=None):
+ """
+ Return the cumulative product of elements along a given axis.
+
+ Parameters
+ ----------
+ a : array_like
+ Input array.
+ axis : int, optional
+ Axis along which the cumulative product is computed. By default
+ the input is flattened.
+ dtype : dtype, optional
+ Type of the returned array, as well as of the accumulator in which
+ the elements are multiplied. If *dtype* is not specified, it
+ defaults to the dtype of `a`, unless `a` has an integer dtype with
+ a precision less than that of the default platform integer. In
+ that case, the default platform integer is used instead.
+ out : ndarray, optional
+ Alternative output array in which to place the result. It must
+ have the same shape and buffer length as the expected output
+ but the type of the resulting values will be cast if necessary.
+
+ Returns
+ -------
+ cumprod : ndarray
+ A new array holding the result is returned unless `out` is
+ specified, in which case a reference to out is returned.
+
+ See Also
+ --------
+ cumulative_prod : Array API compatible alternative for ``cumprod``.
+ :ref:`ufuncs-output-type`
+
+ Notes
+ -----
+ Arithmetic is modular when using integer types, and no error is
+ raised on overflow.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([1,2,3])
+ >>> np.cumprod(a) # intermediate results 1, 1*2
+ ... # total product 1*2*3 = 6
+ array([1, 2, 6])
+ >>> a = np.array([[1, 2, 3], [4, 5, 6]])
+ >>> np.cumprod(a, dtype=float) # specify type of output
+ array([ 1., 2., 6., 24., 120., 720.])
+
+ The cumulative product for each column (i.e., over the rows) of `a`:
+
+ >>> np.cumprod(a, axis=0)
+ array([[ 1, 2, 3],
+ [ 4, 10, 18]])
+
+ The cumulative product for each row (i.e. over the columns) of `a`:
+
+ >>> np.cumprod(a,axis=1)
+ array([[ 1, 2, 6],
+ [ 4, 20, 120]])
+
+ """
+ return _wrapfunc(a, 'cumprod', axis=axis, dtype=dtype, out=out)
+
+
+def _ndim_dispatcher(a):
+ return (a,)
+
+
+@array_function_dispatch(_ndim_dispatcher)
+def ndim(a):
+ """
+ Return the number of dimensions of an array.
+
+ Parameters
+ ----------
+ a : array_like
+ Input array. If it is not already an ndarray, a conversion is
+ attempted.
+
+ Returns
+ -------
+ number_of_dimensions : int
+ The number of dimensions in `a`. Scalars are zero-dimensional.
+
+ See Also
+ --------
+ ndarray.ndim : equivalent method
+ shape : dimensions of array
+ ndarray.shape : dimensions of array
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.ndim([[1,2,3],[4,5,6]])
+ 2
+ >>> np.ndim(np.array([[1,2,3],[4,5,6]]))
+ 2
+ >>> np.ndim(1)
+ 0
+
+ """
+ try:
+ return a.ndim
+ except AttributeError:
+ return asarray(a).ndim
+
+
+def _size_dispatcher(a, axis=None):
+ return (a,)
+
+
+@array_function_dispatch(_size_dispatcher)
+def size(a, axis=None):
+ """
+ Return the number of elements along a given axis.
+
+ Parameters
+ ----------
+ a : array_like
+ Input data.
+ axis : int, optional
+ Axis along which the elements are counted. By default, give
+ the total number of elements.
+
+ Returns
+ -------
+ element_count : int
+ Number of elements along the specified axis.
+
+ See Also
+ --------
+ shape : dimensions of array
+ ndarray.shape : dimensions of array
+ ndarray.size : number of elements in array
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[1,2,3],[4,5,6]])
+ >>> np.size(a)
+ 6
+ >>> np.size(a,1)
+ 3
+ >>> np.size(a,0)
+ 2
+
+ """
+ if axis is None:
+ try:
+ return a.size
+ except AttributeError:
+ return asarray(a).size
+ else:
+ try:
+ return a.shape[axis]
+ except AttributeError:
+ return asarray(a).shape[axis]
+
+
+def _round_dispatcher(a, decimals=None, out=None):
+ return (a, out)
+
+
+@array_function_dispatch(_round_dispatcher)
+def round(a, decimals=0, out=None):
+ """
+ Evenly round to the given number of decimals.
+
+ Parameters
+ ----------
+ a : array_like
+ Input data.
+ decimals : int, optional
+ Number of decimal places to round to (default: 0). If
+ decimals is negative, it specifies the number of positions to
+ the left of the decimal point.
+ out : ndarray, optional
+ Alternative output array in which to place the result. It must have
+ the same shape as the expected output, but the type of the output
+ values will be cast if necessary. See :ref:`ufuncs-output-type`
+ for more details.
+
+ Returns
+ -------
+ rounded_array : ndarray
+ An array of the same type as `a`, containing the rounded values.
+ Unless `out` was specified, a new array is created. A reference to
+ the result is returned.
+
+ The real and imaginary parts of complex numbers are rounded
+ separately. The result of rounding a float is a float.
+
+ See Also
+ --------
+ ndarray.round : equivalent method
+ around : an alias for this function
+ ceil, fix, floor, rint, trunc
+
+
+ Notes
+ -----
+ For values exactly halfway between rounded decimal values, NumPy
+ rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0,
+ -0.5 and 0.5 round to 0.0, etc.
+
+ ``np.round`` uses a fast but sometimes inexact algorithm to round
+ floating-point datatypes. For positive `decimals` it is equivalent to
+ ``np.true_divide(np.rint(a * 10**decimals), 10**decimals)``, which has
+ error due to the inexact representation of decimal fractions in the IEEE
+ floating point standard [1]_ and errors introduced when scaling by powers
+ of ten. For instance, note the extra "1" in the following:
+
+ >>> np.round(56294995342131.5, 3)
+ 56294995342131.51
+
+ If your goal is to print such values with a fixed number of decimals, it is
+ preferable to use numpy's float printing routines to limit the number of
+ printed decimals:
+
+ >>> np.format_float_positional(56294995342131.5, precision=3)
+ '56294995342131.5'
+
+ The float printing routines use an accurate but much more computationally
+ demanding algorithm to compute the number of digits after the decimal
+ point.
+
+ Alternatively, Python's builtin `round` function uses a more accurate
+ but slower algorithm for 64-bit floating point values:
+
+ >>> round(56294995342131.5, 3)
+ 56294995342131.5
+ >>> np.round(16.055, 2), round(16.055, 2) # equals 16.0549999999999997
+ (16.06, 16.05)
+
+
+ References
+ ----------
+ .. [1] "Lecture Notes on the Status of IEEE 754", William Kahan,
+ https://people.eecs.berkeley.edu/~wkahan/ieee754status/IEEE754.PDF
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.round([0.37, 1.64])
+ array([0., 2.])
+ >>> np.round([0.37, 1.64], decimals=1)
+ array([0.4, 1.6])
+ >>> np.round([.5, 1.5, 2.5, 3.5, 4.5]) # rounds to nearest even value
+ array([0., 2., 2., 4., 4.])
+ >>> np.round([1,2,3,11], decimals=1) # ndarray of ints is returned
+ array([ 1, 2, 3, 11])
+ >>> np.round([1,2,3,11], decimals=-1)
+ array([ 0, 0, 0, 10])
+
+ """
+ return _wrapfunc(a, 'round', decimals=decimals, out=out)
+
+
+@array_function_dispatch(_round_dispatcher)
+def around(a, decimals=0, out=None):
+ """
+ Round an array to the given number of decimals.
+
+ `around` is an alias of `~numpy.round`.
+
+ See Also
+ --------
+ ndarray.round : equivalent method
+ round : alias for this function
+ ceil, fix, floor, rint, trunc
+
+ """
+ return _wrapfunc(a, 'round', decimals=decimals, out=out)
+
+
+def _mean_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None, *,
+ where=None):
+ return (a, where, out)
+
+
+@array_function_dispatch(_mean_dispatcher)
+def mean(a, axis=None, dtype=None, out=None, keepdims=np._NoValue, *,
+ where=np._NoValue):
+ """
+ Compute the arithmetic mean along the specified axis.
+
+ Returns the average of the array elements. The average is taken over
+ the flattened array by default, otherwise over the specified axis.
+ `float64` intermediate and return values are used for integer inputs.
+
+ Parameters
+ ----------
+ a : array_like
+ Array containing numbers whose mean is desired. If `a` is not an
+ array, a conversion is attempted.
+ axis : None or int or tuple of ints, optional
+ Axis or axes along which the means are computed. The default is to
+ compute the mean of the flattened array.
+
+ If this is a tuple of ints, a mean is performed over multiple axes,
+ instead of a single axis or all the axes as before.
+ dtype : data-type, optional
+ Type to use in computing the mean. For integer inputs, the default
+ is `float64`; for floating point inputs, it is the same as the
+ input dtype.
+ out : ndarray, optional
+ Alternate output array in which to place the result. The default
+ is ``None``; if provided, it must have the same shape as the
+ expected output, but the type will be cast if necessary.
+ See :ref:`ufuncs-output-type` for more details.
+ See :ref:`ufuncs-output-type` for more details.
+
+ keepdims : bool, optional
+ If this is set to True, the axes which are reduced are left
+ in the result as dimensions with size one. With this option,
+ the result will broadcast correctly against the input array.
+
+ If the default value is passed, then `keepdims` will not be
+ passed through to the `mean` method of sub-classes of
+ `ndarray`, however any non-default value will be. If the
+ sub-class' method does not implement `keepdims` any
+ exceptions will be raised.
+
+ where : array_like of bool, optional
+ Elements to include in the mean. See `~numpy.ufunc.reduce` for details.
+
+ .. versionadded:: 1.20.0
+
+ Returns
+ -------
+ m : ndarray, see dtype parameter above
+ If `out=None`, returns a new array containing the mean values,
+ otherwise a reference to the output array is returned.
+
+ See Also
+ --------
+ average : Weighted average
+ std, var, nanmean, nanstd, nanvar
+
+ Notes
+ -----
+ The arithmetic mean is the sum of the elements along the axis divided
+ by the number of elements.
+
+ Note that for floating-point input, the mean is computed using the
+ same precision the input has. Depending on the input data, this can
+ cause the results to be inaccurate, especially for `float32` (see
+ example below). Specifying a higher-precision accumulator using the
+ `dtype` keyword can alleviate this issue.
+
+ By default, `float16` results are computed using `float32` intermediates
+ for extra precision.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[1, 2], [3, 4]])
+ >>> np.mean(a)
+ 2.5
+ >>> np.mean(a, axis=0)
+ array([2., 3.])
+ >>> np.mean(a, axis=1)
+ array([1.5, 3.5])
+
+ In single precision, `mean` can be inaccurate:
+
+ >>> a = np.zeros((2, 512*512), dtype=np.float32)
+ >>> a[0, :] = 1.0
+ >>> a[1, :] = 0.1
+ >>> np.mean(a)
+ np.float32(0.54999924)
+
+ Computing the mean in float64 is more accurate:
+
+ >>> np.mean(a, dtype=np.float64)
+ 0.55000000074505806 # may vary
+
+ Computing the mean in timedelta64 is available:
+
+ >>> b = np.array([1, 3], dtype="timedelta64[D]")
+ >>> np.mean(b)
+ np.timedelta64(2,'D')
+
+ Specifying a where argument:
+
+ >>> a = np.array([[5, 9, 13], [14, 10, 12], [11, 15, 19]])
+ >>> np.mean(a)
+ 12.0
+ >>> np.mean(a, where=[[True], [False], [False]])
+ 9.0
+
+ """
+ kwargs = {}
+ if keepdims is not np._NoValue:
+ kwargs['keepdims'] = keepdims
+ if where is not np._NoValue:
+ kwargs['where'] = where
+ if type(a) is not mu.ndarray:
+ try:
+ mean = a.mean
+ except AttributeError:
+ pass
+ else:
+ return mean(axis=axis, dtype=dtype, out=out, **kwargs)
+
+ return _methods._mean(a, axis=axis, dtype=dtype,
+ out=out, **kwargs)
+
+
+def _std_dispatcher(a, axis=None, dtype=None, out=None, ddof=None,
+ keepdims=None, *, where=None, mean=None, correction=None):
+ return (a, where, out, mean)
+
+
+@array_function_dispatch(_std_dispatcher)
+def std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue, *,
+ where=np._NoValue, mean=np._NoValue, correction=np._NoValue):
+ r"""
+ Compute the standard deviation along the specified axis.
+
+ Returns the standard deviation, a measure of the spread of a distribution,
+ of the array elements. The standard deviation is computed for the
+ flattened array by default, otherwise over the specified axis.
+
+ Parameters
+ ----------
+ a : array_like
+ Calculate the standard deviation of these values.
+ axis : None or int or tuple of ints, optional
+ Axis or axes along which the standard deviation is computed. The
+ default is to compute the standard deviation of the flattened array.
+ If this is a tuple of ints, a standard deviation is performed over
+ multiple axes, instead of a single axis or all the axes as before.
+ dtype : dtype, optional
+ Type to use in computing the standard deviation. For arrays of
+ integer type the default is float64, for arrays of float types it is
+ the same as the array type.
+ out : ndarray, optional
+ Alternative output array in which to place the result. It must have
+ the same shape as the expected output but the type (of the calculated
+ values) will be cast if necessary.
+ See :ref:`ufuncs-output-type` for more details.
+ ddof : {int, float}, optional
+ Means Delta Degrees of Freedom. The divisor used in calculations
+ is ``N - ddof``, where ``N`` represents the number of elements.
+ By default `ddof` is zero. See Notes for details about use of `ddof`.
+ keepdims : bool, optional
+ If this is set to True, the axes which are reduced are left
+ in the result as dimensions with size one. With this option,
+ the result will broadcast correctly against the input array.
+
+ If the default value is passed, then `keepdims` will not be
+ passed through to the `std` method of sub-classes of
+ `ndarray`, however any non-default value will be. If the
+ sub-class' method does not implement `keepdims` any
+ exceptions will be raised.
+ where : array_like of bool, optional
+ Elements to include in the standard deviation.
+ See `~numpy.ufunc.reduce` for details.
+
+ .. versionadded:: 1.20.0
+
+ mean : array_like, optional
+ Provide the mean to prevent its recalculation. The mean should have
+ a shape as if it was calculated with ``keepdims=True``.
+ The axis for the calculation of the mean should be the same as used in
+ the call to this std function.
+
+ .. versionadded:: 2.0.0
+
+ correction : {int, float}, optional
+ Array API compatible name for the ``ddof`` parameter. Only one of them
+ can be provided at the same time.
+
+ .. versionadded:: 2.0.0
+
+ Returns
+ -------
+ standard_deviation : ndarray, see dtype parameter above.
+ If `out` is None, return a new array containing the standard deviation,
+ otherwise return a reference to the output array.
+
+ See Also
+ --------
+ var, mean, nanmean, nanstd, nanvar
+ :ref:`ufuncs-output-type`
+
+ Notes
+ -----
+ There are several common variants of the array standard deviation
+ calculation. Assuming the input `a` is a one-dimensional NumPy array
+ and ``mean`` is either provided as an argument or computed as
+ ``a.mean()``, NumPy computes the standard deviation of an array as::
+
+ N = len(a)
+ d2 = abs(a - mean)**2 # abs is for complex `a`
+ var = d2.sum() / (N - ddof) # note use of `ddof`
+ std = var**0.5
+
+ Different values of the argument `ddof` are useful in different
+ contexts. NumPy's default ``ddof=0`` corresponds with the expression:
+
+ .. math::
+
+ \sqrt{\frac{\sum_i{|a_i - \bar{a}|^2 }}{N}}
+
+ which is sometimes called the "population standard deviation" in the field
+ of statistics because it applies the definition of standard deviation to
+ `a` as if `a` were a complete population of possible observations.
+
+ Many other libraries define the standard deviation of an array
+ differently, e.g.:
+
+ .. math::
+
+ \sqrt{\frac{\sum_i{|a_i - \bar{a}|^2 }}{N - 1}}
+
+ In statistics, the resulting quantity is sometimes called the "sample
+ standard deviation" because if `a` is a random sample from a larger
+ population, this calculation provides the square root of an unbiased
+ estimate of the variance of the population. The use of :math:`N-1` in the
+ denominator is often called "Bessel's correction" because it corrects for
+ bias (toward lower values) in the variance estimate introduced when the
+ sample mean of `a` is used in place of the true mean of the population.
+ The resulting estimate of the standard deviation is still biased, but less
+ than it would have been without the correction. For this quantity, use
+ ``ddof=1``.
+
+ Note that, for complex numbers, `std` takes the absolute
+ value before squaring, so that the result is always real and nonnegative.
+
+ For floating-point input, the standard deviation is computed using the same
+ precision the input has. Depending on the input data, this can cause
+ the results to be inaccurate, especially for float32 (see example below).
+ Specifying a higher-accuracy accumulator using the `dtype` keyword can
+ alleviate this issue.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[1, 2], [3, 4]])
+ >>> np.std(a)
+ 1.1180339887498949 # may vary
+ >>> np.std(a, axis=0)
+ array([1., 1.])
+ >>> np.std(a, axis=1)
+ array([0.5, 0.5])
+
+ In single precision, std() can be inaccurate:
+
+ >>> a = np.zeros((2, 512*512), dtype=np.float32)
+ >>> a[0, :] = 1.0
+ >>> a[1, :] = 0.1
+ >>> np.std(a)
+ np.float32(0.45000005)
+
+ Computing the standard deviation in float64 is more accurate:
+
+ >>> np.std(a, dtype=np.float64)
+ 0.44999999925494177 # may vary
+
+ Specifying a where argument:
+
+ >>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
+ >>> np.std(a)
+ 2.614064523559687 # may vary
+ >>> np.std(a, where=[[True], [True], [False]])
+ 2.0
+
+ Using the mean keyword to save computation time:
+
+ >>> import numpy as np
+ >>> from timeit import timeit
+ >>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
+ >>> mean = np.mean(a, axis=1, keepdims=True)
+ >>>
+ >>> g = globals()
+ >>> n = 10000
+ >>> t1 = timeit("std = np.std(a, axis=1, mean=mean)", globals=g, number=n)
+ >>> t2 = timeit("std = np.std(a, axis=1)", globals=g, number=n)
+ >>> print(f'Percentage execution time saved {100*(t2-t1)/t2:.0f}%')
+ #doctest: +SKIP
+ Percentage execution time saved 30%
+
+ """
+ kwargs = {}
+ if keepdims is not np._NoValue:
+ kwargs['keepdims'] = keepdims
+ if where is not np._NoValue:
+ kwargs['where'] = where
+ if mean is not np._NoValue:
+ kwargs['mean'] = mean
+
+ if correction != np._NoValue:
+ if ddof != 0:
+ raise ValueError(
+ "ddof and correction can't be provided simultaneously."
+ )
+ else:
+ ddof = correction
+
+ if type(a) is not mu.ndarray:
+ try:
+ std = a.std
+ except AttributeError:
+ pass
+ else:
+ return std(axis=axis, dtype=dtype, out=out, ddof=ddof, **kwargs)
+
+ return _methods._std(a, axis=axis, dtype=dtype, out=out, ddof=ddof,
+ **kwargs)
+
+
+def _var_dispatcher(a, axis=None, dtype=None, out=None, ddof=None,
+ keepdims=None, *, where=None, mean=None, correction=None):
+ return (a, where, out, mean)
+
+
+@array_function_dispatch(_var_dispatcher)
+def var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue, *,
+ where=np._NoValue, mean=np._NoValue, correction=np._NoValue):
+ r"""
+ Compute the variance along the specified axis.
+
+ Returns the variance of the array elements, a measure of the spread of a
+ distribution. The variance is computed for the flattened array by
+ default, otherwise over the specified axis.
+
+ Parameters
+ ----------
+ a : array_like
+ Array containing numbers whose variance is desired. If `a` is not an
+ array, a conversion is attempted.
+ axis : None or int or tuple of ints, optional
+ Axis or axes along which the variance is computed. The default is to
+ compute the variance of the flattened array.
+ If this is a tuple of ints, a variance is performed over multiple axes,
+ instead of a single axis or all the axes as before.
+ dtype : data-type, optional
+ Type to use in computing the variance. For arrays of integer type
+ the default is `float64`; for arrays of float types it is the same as
+ the array type.
+ out : ndarray, optional
+ Alternate output array in which to place the result. It must have
+ the same shape as the expected output, but the type is cast if
+ necessary.
+ ddof : {int, float}, optional
+ "Delta Degrees of Freedom": the divisor used in the calculation is
+ ``N - ddof``, where ``N`` represents the number of elements. By
+ default `ddof` is zero. See notes for details about use of `ddof`.
+ keepdims : bool, optional
+ If this is set to True, the axes which are reduced are left
+ in the result as dimensions with size one. With this option,
+ the result will broadcast correctly against the input array.
+
+ If the default value is passed, then `keepdims` will not be
+ passed through to the `var` method of sub-classes of
+ `ndarray`, however any non-default value will be. If the
+ sub-class' method does not implement `keepdims` any
+ exceptions will be raised.
+ where : array_like of bool, optional
+ Elements to include in the variance. See `~numpy.ufunc.reduce` for
+ details.
+
+ .. versionadded:: 1.20.0
+
+ mean : array like, optional
+ Provide the mean to prevent its recalculation. The mean should have
+ a shape as if it was calculated with ``keepdims=True``.
+ The axis for the calculation of the mean should be the same as used in
+ the call to this var function.
+
+ .. versionadded:: 2.0.0
+
+ correction : {int, float}, optional
+ Array API compatible name for the ``ddof`` parameter. Only one of them
+ can be provided at the same time.
+
+ .. versionadded:: 2.0.0
+
+ Returns
+ -------
+ variance : ndarray, see dtype parameter above
+ If ``out=None``, returns a new array containing the variance;
+ otherwise, a reference to the output array is returned.
+
+ See Also
+ --------
+ std, mean, nanmean, nanstd, nanvar
+ :ref:`ufuncs-output-type`
+
+ Notes
+ -----
+ There are several common variants of the array variance calculation.
+ Assuming the input `a` is a one-dimensional NumPy array and ``mean`` is
+ either provided as an argument or computed as ``a.mean()``, NumPy
+ computes the variance of an array as::
+
+ N = len(a)
+ d2 = abs(a - mean)**2 # abs is for complex `a`
+ var = d2.sum() / (N - ddof) # note use of `ddof`
+
+ Different values of the argument `ddof` are useful in different
+ contexts. NumPy's default ``ddof=0`` corresponds with the expression:
+
+ .. math::
+
+ \frac{\sum_i{|a_i - \bar{a}|^2 }}{N}
+
+ which is sometimes called the "population variance" in the field of
+ statistics because it applies the definition of variance to `a` as if `a`
+ were a complete population of possible observations.
+
+ Many other libraries define the variance of an array differently, e.g.:
+
+ .. math::
+
+ \frac{\sum_i{|a_i - \bar{a}|^2}}{N - 1}
+
+ In statistics, the resulting quantity is sometimes called the "sample
+ variance" because if `a` is a random sample from a larger population,
+ this calculation provides an unbiased estimate of the variance of the
+ population. The use of :math:`N-1` in the denominator is often called
+ "Bessel's correction" because it corrects for bias (toward lower values)
+ in the variance estimate introduced when the sample mean of `a` is used
+ in place of the true mean of the population. For this quantity, use
+ ``ddof=1``.
+
+ Note that for complex numbers, the absolute value is taken before
+ squaring, so that the result is always real and nonnegative.
+
+ For floating-point input, the variance is computed using the same
+ precision the input has. Depending on the input data, this can cause
+ the results to be inaccurate, especially for `float32` (see example
+ below). Specifying a higher-accuracy accumulator using the ``dtype``
+ keyword can alleviate this issue.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[1, 2], [3, 4]])
+ >>> np.var(a)
+ 1.25
+ >>> np.var(a, axis=0)
+ array([1., 1.])
+ >>> np.var(a, axis=1)
+ array([0.25, 0.25])
+
+ In single precision, var() can be inaccurate:
+
+ >>> a = np.zeros((2, 512*512), dtype=np.float32)
+ >>> a[0, :] = 1.0
+ >>> a[1, :] = 0.1
+ >>> np.var(a)
+ np.float32(0.20250003)
+
+ Computing the variance in float64 is more accurate:
+
+ >>> np.var(a, dtype=np.float64)
+ 0.20249999932944759 # may vary
+ >>> ((1-0.55)**2 + (0.1-0.55)**2)/2
+ 0.2025
+
+ Specifying a where argument:
+
+ >>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
+ >>> np.var(a)
+ 6.833333333333333 # may vary
+ >>> np.var(a, where=[[True], [True], [False]])
+ 4.0
+
+ Using the mean keyword to save computation time:
+
+ >>> import numpy as np
+ >>> from timeit import timeit
+ >>>
+ >>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
+ >>> mean = np.mean(a, axis=1, keepdims=True)
+ >>>
+ >>> g = globals()
+ >>> n = 10000
+ >>> t1 = timeit("var = np.var(a, axis=1, mean=mean)", globals=g, number=n)
+ >>> t2 = timeit("var = np.var(a, axis=1)", globals=g, number=n)
+ >>> print(f'Percentage execution time saved {100*(t2-t1)/t2:.0f}%')
+ #doctest: +SKIP
+ Percentage execution time saved 32%
+
+ """
+ kwargs = {}
+ if keepdims is not np._NoValue:
+ kwargs['keepdims'] = keepdims
+ if where is not np._NoValue:
+ kwargs['where'] = where
+ if mean is not np._NoValue:
+ kwargs['mean'] = mean
+
+ if correction != np._NoValue:
+ if ddof != 0:
+ raise ValueError(
+ "ddof and correction can't be provided simultaneously."
+ )
+ else:
+ ddof = correction
+
+ if type(a) is not mu.ndarray:
+ try:
+ var = a.var
+
+ except AttributeError:
+ pass
+ else:
+ return var(axis=axis, dtype=dtype, out=out, ddof=ddof, **kwargs)
+
+ return _methods._var(a, axis=axis, dtype=dtype, out=out, ddof=ddof,
+ **kwargs)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/fromnumeric.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/fromnumeric.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..48648593d72f0d14d16f5ce8a7bd18b2a3707bec
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/fromnumeric.pyi
@@ -0,0 +1,1733 @@
+# ruff: noqa: ANN401
+from collections.abc import Sequence
+from typing import (
+ Any,
+ Literal,
+ Protocol,
+ SupportsIndex,
+ TypeAlias,
+ TypeVar,
+ overload,
+ type_check_only,
+)
+
+from _typeshed import Incomplete
+from typing_extensions import Never, deprecated
+
+import numpy as np
+from numpy import (
+ number,
+ uint64,
+ int_,
+ int64,
+ intp,
+ float16,
+ floating,
+ complexfloating,
+ timedelta64,
+ object_,
+ generic,
+ _AnyShapeType,
+ _OrderKACF,
+ _OrderACF,
+ _ModeKind,
+ _PartitionKind,
+ _SortKind,
+ _SortSide,
+ _CastingKind,
+)
+from numpy._globals import _NoValueType
+from numpy._typing import (
+ DTypeLike,
+ _DTypeLike,
+ ArrayLike,
+ _ArrayLike,
+ NDArray,
+ _NestedSequence,
+ _ShapeLike,
+ _ArrayLikeBool_co,
+ _ArrayLikeUInt_co,
+ _ArrayLikeInt,
+ _ArrayLikeInt_co,
+ _ArrayLikeFloat_co,
+ _ArrayLikeComplex_co,
+ _ArrayLikeObject_co,
+ _IntLike_co,
+ _BoolLike_co,
+ _ComplexLike_co,
+ _NumberLike_co,
+ _ScalarLike_co,
+)
+
+__all__ = [
+ "all",
+ "amax",
+ "amin",
+ "any",
+ "argmax",
+ "argmin",
+ "argpartition",
+ "argsort",
+ "around",
+ "choose",
+ "clip",
+ "compress",
+ "cumprod",
+ "cumsum",
+ "cumulative_prod",
+ "cumulative_sum",
+ "diagonal",
+ "mean",
+ "max",
+ "min",
+ "matrix_transpose",
+ "ndim",
+ "nonzero",
+ "partition",
+ "prod",
+ "ptp",
+ "put",
+ "ravel",
+ "repeat",
+ "reshape",
+ "resize",
+ "round",
+ "searchsorted",
+ "shape",
+ "size",
+ "sort",
+ "squeeze",
+ "std",
+ "sum",
+ "swapaxes",
+ "take",
+ "trace",
+ "transpose",
+ "var",
+]
+
+_SCT = TypeVar("_SCT", bound=generic)
+_SCT_uifcO = TypeVar("_SCT_uifcO", bound=number[Any] | object_)
+_ArrayT = TypeVar("_ArrayT", bound=np.ndarray[Any, Any])
+_ShapeType = TypeVar("_ShapeType", bound=tuple[int, ...])
+_ShapeType_co = TypeVar("_ShapeType_co", bound=tuple[int, ...], covariant=True)
+
+@type_check_only
+class _SupportsShape(Protocol[_ShapeType_co]):
+ # NOTE: it matters that `self` is positional only
+ @property
+ def shape(self, /) -> _ShapeType_co: ...
+
+# a "sequence" that isn't a string, bytes, bytearray, or memoryview
+_T = TypeVar("_T")
+_PyArray: TypeAlias = list[_T] | tuple[_T, ...]
+# `int` also covers `bool`
+_PyScalar: TypeAlias = float | complex | bytes | str
+
+@overload
+def take(
+ a: _ArrayLike[_SCT],
+ indices: _IntLike_co,
+ axis: None = ...,
+ out: None = ...,
+ mode: _ModeKind = ...,
+) -> _SCT: ...
+@overload
+def take(
+ a: ArrayLike,
+ indices: _IntLike_co,
+ axis: SupportsIndex | None = ...,
+ out: None = ...,
+ mode: _ModeKind = ...,
+) -> Any: ...
+@overload
+def take(
+ a: _ArrayLike[_SCT],
+ indices: _ArrayLikeInt_co,
+ axis: SupportsIndex | None = ...,
+ out: None = ...,
+ mode: _ModeKind = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def take(
+ a: ArrayLike,
+ indices: _ArrayLikeInt_co,
+ axis: SupportsIndex | None = ...,
+ out: None = ...,
+ mode: _ModeKind = ...,
+) -> NDArray[Any]: ...
+@overload
+def take(
+ a: ArrayLike,
+ indices: _ArrayLikeInt_co,
+ axis: SupportsIndex | None,
+ out: _ArrayT,
+ mode: _ModeKind = ...,
+) -> _ArrayT: ...
+@overload
+def take(
+ a: ArrayLike,
+ indices: _ArrayLikeInt_co,
+ axis: SupportsIndex | None = ...,
+ *,
+ out: _ArrayT,
+ mode: _ModeKind = ...,
+) -> _ArrayT: ...
+
+@overload
+def reshape( # shape: index
+ a: _ArrayLike[_SCT],
+ /,
+ shape: SupportsIndex,
+ order: _OrderACF = "C",
+ *,
+ copy: bool | None = None,
+) -> np.ndarray[tuple[int], np.dtype[_SCT]]: ...
+@overload
+def reshape( # shape: (int, ...) @ _AnyShapeType
+ a: _ArrayLike[_SCT],
+ /,
+ shape: _AnyShapeType,
+ order: _OrderACF = "C",
+ *,
+ copy: bool | None = None,
+) -> np.ndarray[_AnyShapeType, np.dtype[_SCT]]: ...
+@overload # shape: Sequence[index]
+def reshape(
+ a: _ArrayLike[_SCT],
+ /,
+ shape: Sequence[SupportsIndex],
+ order: _OrderACF = "C",
+ *,
+ copy: bool | None = None,
+) -> NDArray[_SCT]: ...
+@overload # shape: index
+def reshape(
+ a: ArrayLike,
+ /,
+ shape: SupportsIndex,
+ order: _OrderACF = "C",
+ *,
+ copy: bool | None = None,
+) -> np.ndarray[tuple[int], np.dtype[Any]]: ...
+@overload
+def reshape( # shape: (int, ...) @ _AnyShapeType
+ a: ArrayLike,
+ /,
+ shape: _AnyShapeType,
+ order: _OrderACF = "C",
+ *,
+ copy: bool | None = None,
+) -> np.ndarray[_AnyShapeType, np.dtype[Any]]: ...
+@overload # shape: Sequence[index]
+def reshape(
+ a: ArrayLike,
+ /,
+ shape: Sequence[SupportsIndex],
+ order: _OrderACF = "C",
+ *,
+ copy: bool | None = None,
+) -> NDArray[Any]: ...
+@overload
+@deprecated(
+ "`newshape` keyword argument is deprecated, "
+ "use `shape=...` or pass shape positionally instead. "
+ "(deprecated in NumPy 2.1)",
+)
+def reshape(
+ a: ArrayLike,
+ /,
+ shape: None = None,
+ order: _OrderACF = "C",
+ *,
+ newshape: _ShapeLike,
+ copy: bool | None = None,
+) -> NDArray[Any]: ...
+
+@overload
+def choose(
+ a: _IntLike_co,
+ choices: ArrayLike,
+ out: None = ...,
+ mode: _ModeKind = ...,
+) -> Any: ...
+@overload
+def choose(
+ a: _ArrayLikeInt_co,
+ choices: _ArrayLike[_SCT],
+ out: None = ...,
+ mode: _ModeKind = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def choose(
+ a: _ArrayLikeInt_co,
+ choices: ArrayLike,
+ out: None = ...,
+ mode: _ModeKind = ...,
+) -> NDArray[Any]: ...
+@overload
+def choose(
+ a: _ArrayLikeInt_co,
+ choices: ArrayLike,
+ out: _ArrayT,
+ mode: _ModeKind = ...,
+) -> _ArrayT: ...
+
+@overload
+def repeat(
+ a: _ArrayLike[_SCT],
+ repeats: _ArrayLikeInt_co,
+ axis: SupportsIndex | None = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def repeat(
+ a: ArrayLike,
+ repeats: _ArrayLikeInt_co,
+ axis: SupportsIndex | None = ...,
+) -> NDArray[Any]: ...
+
+def put(
+ a: NDArray[Any],
+ ind: _ArrayLikeInt_co,
+ v: ArrayLike,
+ mode: _ModeKind = ...,
+) -> None: ...
+
+@overload
+def swapaxes(
+ a: _ArrayLike[_SCT],
+ axis1: SupportsIndex,
+ axis2: SupportsIndex,
+) -> NDArray[_SCT]: ...
+@overload
+def swapaxes(
+ a: ArrayLike,
+ axis1: SupportsIndex,
+ axis2: SupportsIndex,
+) -> NDArray[Any]: ...
+
+@overload
+def transpose(
+ a: _ArrayLike[_SCT],
+ axes: _ShapeLike | None = ...
+) -> NDArray[_SCT]: ...
+@overload
+def transpose(
+ a: ArrayLike,
+ axes: _ShapeLike | None = ...
+) -> NDArray[Any]: ...
+
+@overload
+def matrix_transpose(x: _ArrayLike[_SCT], /) -> NDArray[_SCT]: ...
+@overload
+def matrix_transpose(x: ArrayLike, /) -> NDArray[Any]: ...
+
+#
+@overload
+def partition(
+ a: _ArrayLike[_SCT],
+ kth: _ArrayLikeInt,
+ axis: SupportsIndex | None = -1,
+ kind: _PartitionKind = "introselect",
+ order: None = None,
+) -> NDArray[_SCT]: ...
+@overload
+def partition(
+ a: _ArrayLike[np.void],
+ kth: _ArrayLikeInt,
+ axis: SupportsIndex | None = -1,
+ kind: _PartitionKind = "introselect",
+ order: str | Sequence[str] | None = None,
+) -> NDArray[np.void]: ...
+@overload
+def partition(
+ a: ArrayLike,
+ kth: _ArrayLikeInt,
+ axis: SupportsIndex | None = -1,
+ kind: _PartitionKind = "introselect",
+ order: str | Sequence[str] | None = None,
+) -> NDArray[Any]: ...
+
+#
+def argpartition(
+ a: ArrayLike,
+ kth: _ArrayLikeInt,
+ axis: SupportsIndex | None = -1,
+ kind: _PartitionKind = "introselect",
+ order: str | Sequence[str] | None = None,
+) -> NDArray[intp]: ...
+
+#
+@overload
+def sort(
+ a: _ArrayLike[_SCT],
+ axis: SupportsIndex | None = ...,
+ kind: _SortKind | None = ...,
+ order: str | Sequence[str] | None = ...,
+ *,
+ stable: bool | None = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def sort(
+ a: ArrayLike,
+ axis: SupportsIndex | None = ...,
+ kind: _SortKind | None = ...,
+ order: str | Sequence[str] | None = ...,
+ *,
+ stable: bool | None = ...,
+) -> NDArray[Any]: ...
+
+def argsort(
+ a: ArrayLike,
+ axis: SupportsIndex | None = ...,
+ kind: _SortKind | None = ...,
+ order: str | Sequence[str] | None = ...,
+ *,
+ stable: bool | None = ...,
+) -> NDArray[intp]: ...
+
+@overload
+def argmax(
+ a: ArrayLike,
+ axis: None = ...,
+ out: None = ...,
+ *,
+ keepdims: Literal[False] = ...,
+) -> intp: ...
+@overload
+def argmax(
+ a: ArrayLike,
+ axis: SupportsIndex | None = ...,
+ out: None = ...,
+ *,
+ keepdims: bool = ...,
+) -> Any: ...
+@overload
+def argmax(
+ a: ArrayLike,
+ axis: SupportsIndex | None,
+ out: _ArrayT,
+ *,
+ keepdims: bool = ...,
+) -> _ArrayT: ...
+@overload
+def argmax(
+ a: ArrayLike,
+ axis: SupportsIndex | None = ...,
+ *,
+ out: _ArrayT,
+ keepdims: bool = ...,
+) -> _ArrayT: ...
+
+@overload
+def argmin(
+ a: ArrayLike,
+ axis: None = ...,
+ out: None = ...,
+ *,
+ keepdims: Literal[False] = ...,
+) -> intp: ...
+@overload
+def argmin(
+ a: ArrayLike,
+ axis: SupportsIndex | None = ...,
+ out: None = ...,
+ *,
+ keepdims: bool = ...,
+) -> Any: ...
+@overload
+def argmin(
+ a: ArrayLike,
+ axis: SupportsIndex | None,
+ out: _ArrayT,
+ *,
+ keepdims: bool = ...,
+) -> _ArrayT: ...
+@overload
+def argmin(
+ a: ArrayLike,
+ axis: SupportsIndex | None = ...,
+ *,
+ out: _ArrayT,
+ keepdims: bool = ...,
+) -> _ArrayT: ...
+
+@overload
+def searchsorted(
+ a: ArrayLike,
+ v: _ScalarLike_co,
+ side: _SortSide = ...,
+ sorter: _ArrayLikeInt_co | None = ..., # 1D int array
+) -> intp: ...
+@overload
+def searchsorted(
+ a: ArrayLike,
+ v: ArrayLike,
+ side: _SortSide = ...,
+ sorter: _ArrayLikeInt_co | None = ..., # 1D int array
+) -> NDArray[intp]: ...
+
+#
+@overload
+def resize(a: _ArrayLike[_SCT], new_shape: SupportsIndex | tuple[SupportsIndex]) -> np.ndarray[tuple[int], np.dtype[_SCT]]: ...
+@overload
+def resize(a: _ArrayLike[_SCT], new_shape: _AnyShapeType) -> np.ndarray[_AnyShapeType, np.dtype[_SCT]]: ...
+@overload
+def resize(a: _ArrayLike[_SCT], new_shape: _ShapeLike) -> NDArray[_SCT]: ...
+@overload
+def resize(a: ArrayLike, new_shape: SupportsIndex | tuple[SupportsIndex]) -> np.ndarray[tuple[int], np.dtype[Any]]: ...
+@overload
+def resize(a: ArrayLike, new_shape: _AnyShapeType) -> np.ndarray[_AnyShapeType, np.dtype[Any]]: ...
+@overload
+def resize(a: ArrayLike, new_shape: _ShapeLike) -> NDArray[Any]: ...
+
+@overload
+def squeeze(
+ a: _SCT,
+ axis: _ShapeLike | None = ...,
+) -> _SCT: ...
+@overload
+def squeeze(
+ a: _ArrayLike[_SCT],
+ axis: _ShapeLike | None = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def squeeze(
+ a: ArrayLike,
+ axis: _ShapeLike | None = ...,
+) -> NDArray[Any]: ...
+
+@overload
+def diagonal(
+ a: _ArrayLike[_SCT],
+ offset: SupportsIndex = ...,
+ axis1: SupportsIndex = ...,
+ axis2: SupportsIndex = ..., # >= 2D array
+) -> NDArray[_SCT]: ...
+@overload
+def diagonal(
+ a: ArrayLike,
+ offset: SupportsIndex = ...,
+ axis1: SupportsIndex = ...,
+ axis2: SupportsIndex = ..., # >= 2D array
+) -> NDArray[Any]: ...
+
+@overload
+def trace(
+ a: ArrayLike, # >= 2D array
+ offset: SupportsIndex = ...,
+ axis1: SupportsIndex = ...,
+ axis2: SupportsIndex = ...,
+ dtype: DTypeLike = ...,
+ out: None = ...,
+) -> Any: ...
+@overload
+def trace(
+ a: ArrayLike, # >= 2D array
+ offset: SupportsIndex,
+ axis1: SupportsIndex,
+ axis2: SupportsIndex,
+ dtype: DTypeLike,
+ out: _ArrayT,
+) -> _ArrayT: ...
+@overload
+def trace(
+ a: ArrayLike, # >= 2D array
+ offset: SupportsIndex = ...,
+ axis1: SupportsIndex = ...,
+ axis2: SupportsIndex = ...,
+ dtype: DTypeLike = ...,
+ *,
+ out: _ArrayT,
+) -> _ArrayT: ...
+
+_Array1D: TypeAlias = np.ndarray[tuple[int], np.dtype[_SCT]]
+
+@overload
+def ravel(a: _ArrayLike[_SCT], order: _OrderKACF = "C") -> _Array1D[_SCT]: ...
+@overload
+def ravel(a: bytes | _NestedSequence[bytes], order: _OrderKACF = "C") -> _Array1D[np.bytes_]: ...
+@overload
+def ravel(a: str | _NestedSequence[str], order: _OrderKACF = "C") -> _Array1D[np.str_]: ...
+@overload
+def ravel(a: bool | _NestedSequence[bool], order: _OrderKACF = "C") -> _Array1D[np.bool]: ...
+@overload
+def ravel(a: int | _NestedSequence[int], order: _OrderKACF = "C") -> _Array1D[np.int_ | np.bool]: ...
+@overload
+def ravel(a: float | _NestedSequence[float], order: _OrderKACF = "C") -> _Array1D[np.float64 | np.int_ | np.bool]: ...
+@overload
+def ravel(
+ a: complex | _NestedSequence[complex],
+ order: _OrderKACF = "C",
+) -> _Array1D[np.complex128 | np.float64 | np.int_ | np.bool]: ...
+@overload
+def ravel(a: ArrayLike, order: _OrderKACF = "C") -> np.ndarray[tuple[int], np.dtype[Any]]: ...
+
+def nonzero(a: _ArrayLike[Any]) -> tuple[NDArray[intp], ...]: ...
+
+# this prevents `Any` from being returned with Pyright
+@overload
+def shape(a: _SupportsShape[Never]) -> tuple[int, ...]: ...
+@overload
+def shape(a: _SupportsShape[_ShapeType]) -> _ShapeType: ...
+@overload
+def shape(a: _PyScalar) -> tuple[()]: ...
+# `collections.abc.Sequence` can't be used hesre, since `bytes` and `str` are
+# subtypes of it, which would make the return types incompatible.
+@overload
+def shape(a: _PyArray[_PyScalar]) -> tuple[int]: ...
+@overload
+def shape(a: _PyArray[_PyArray[_PyScalar]]) -> tuple[int, int]: ...
+# this overload will be skipped by typecheckers that don't support PEP 688
+@overload
+def shape(a: memoryview | bytearray) -> tuple[int]: ...
+@overload
+def shape(a: ArrayLike) -> tuple[int, ...]: ...
+
+@overload
+def compress(
+ condition: _ArrayLikeBool_co, # 1D bool array
+ a: _ArrayLike[_SCT],
+ axis: SupportsIndex | None = ...,
+ out: None = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def compress(
+ condition: _ArrayLikeBool_co, # 1D bool array
+ a: ArrayLike,
+ axis: SupportsIndex | None = ...,
+ out: None = ...,
+) -> NDArray[Any]: ...
+@overload
+def compress(
+ condition: _ArrayLikeBool_co, # 1D bool array
+ a: ArrayLike,
+ axis: SupportsIndex | None,
+ out: _ArrayT,
+) -> _ArrayT: ...
+@overload
+def compress(
+ condition: _ArrayLikeBool_co, # 1D bool array
+ a: ArrayLike,
+ axis: SupportsIndex | None = ...,
+ *,
+ out: _ArrayT,
+) -> _ArrayT: ...
+
+@overload
+def clip(
+ a: _SCT,
+ a_min: ArrayLike | None,
+ a_max: ArrayLike | None,
+ out: None = ...,
+ *,
+ min: ArrayLike | None = ...,
+ max: ArrayLike | None = ...,
+ dtype: None = ...,
+ where: _ArrayLikeBool_co | None = ...,
+ order: _OrderKACF = ...,
+ subok: bool = ...,
+ signature: str | tuple[str | None, ...] = ...,
+ casting: _CastingKind = ...,
+) -> _SCT: ...
+@overload
+def clip(
+ a: _ScalarLike_co,
+ a_min: ArrayLike | None,
+ a_max: ArrayLike | None,
+ out: None = ...,
+ *,
+ min: ArrayLike | None = ...,
+ max: ArrayLike | None = ...,
+ dtype: None = ...,
+ where: _ArrayLikeBool_co | None = ...,
+ order: _OrderKACF = ...,
+ subok: bool = ...,
+ signature: str | tuple[str | None, ...] = ...,
+ casting: _CastingKind = ...,
+) -> Any: ...
+@overload
+def clip(
+ a: _ArrayLike[_SCT],
+ a_min: ArrayLike | None,
+ a_max: ArrayLike | None,
+ out: None = ...,
+ *,
+ min: ArrayLike | None = ...,
+ max: ArrayLike | None = ...,
+ dtype: None = ...,
+ where: _ArrayLikeBool_co | None = ...,
+ order: _OrderKACF = ...,
+ subok: bool = ...,
+ signature: str | tuple[str | None, ...] = ...,
+ casting: _CastingKind = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def clip(
+ a: ArrayLike,
+ a_min: ArrayLike | None,
+ a_max: ArrayLike | None,
+ out: None = ...,
+ *,
+ min: ArrayLike | None = ...,
+ max: ArrayLike | None = ...,
+ dtype: None = ...,
+ where: _ArrayLikeBool_co | None = ...,
+ order: _OrderKACF = ...,
+ subok: bool = ...,
+ signature: str | tuple[str | None, ...] = ...,
+ casting: _CastingKind = ...,
+) -> NDArray[Any]: ...
+@overload
+def clip(
+ a: ArrayLike,
+ a_min: ArrayLike | None,
+ a_max: ArrayLike | None,
+ out: _ArrayT,
+ *,
+ min: ArrayLike | None = ...,
+ max: ArrayLike | None = ...,
+ dtype: DTypeLike = ...,
+ where: _ArrayLikeBool_co | None = ...,
+ order: _OrderKACF = ...,
+ subok: bool = ...,
+ signature: str | tuple[str | None, ...] = ...,
+ casting: _CastingKind = ...,
+) -> _ArrayT: ...
+@overload
+def clip(
+ a: ArrayLike,
+ a_min: ArrayLike | None,
+ a_max: ArrayLike | None,
+ out: ArrayLike = ...,
+ *,
+ min: ArrayLike | None = ...,
+ max: ArrayLike | None = ...,
+ dtype: DTypeLike,
+ where: _ArrayLikeBool_co | None = ...,
+ order: _OrderKACF = ...,
+ subok: bool = ...,
+ signature: str | tuple[str | None, ...] = ...,
+ casting: _CastingKind = ...,
+) -> Any: ...
+
+@overload
+def sum(
+ a: _ArrayLike[_SCT],
+ axis: None = ...,
+ dtype: None = ...,
+ out: None = ...,
+ keepdims: Literal[False] = ...,
+ initial: _NumberLike_co = ...,
+ where: _ArrayLikeBool_co = ...,
+) -> _SCT: ...
+@overload
+def sum(
+ a: _ArrayLike[_SCT],
+ axis: None = ...,
+ dtype: None = ...,
+ out: None = ...,
+ keepdims: bool = ...,
+ initial: _NumberLike_co = ...,
+ where: _ArrayLikeBool_co = ...,
+) -> _SCT | NDArray[_SCT]: ...
+@overload
+def sum(
+ a: ArrayLike,
+ axis: None,
+ dtype: _DTypeLike[_SCT],
+ out: None = ...,
+ keepdims: Literal[False] = ...,
+ initial: _NumberLike_co = ...,
+ where: _ArrayLikeBool_co = ...,
+) -> _SCT: ...
+@overload
+def sum(
+ a: ArrayLike,
+ axis: None = ...,
+ *,
+ dtype: _DTypeLike[_SCT],
+ out: None = ...,
+ keepdims: Literal[False] = ...,
+ initial: _NumberLike_co = ...,
+ where: _ArrayLikeBool_co = ...,
+) -> _SCT: ...
+@overload
+def sum(
+ a: ArrayLike,
+ axis: _ShapeLike | None,
+ dtype: _DTypeLike[_SCT],
+ out: None = ...,
+ keepdims: bool = ...,
+ initial: _NumberLike_co = ...,
+ where: _ArrayLikeBool_co = ...,
+) -> _SCT | NDArray[_SCT]: ...
+@overload
+def sum(
+ a: ArrayLike,
+ axis: _ShapeLike | None = ...,
+ *,
+ dtype: _DTypeLike[_SCT],
+ out: None = ...,
+ keepdims: bool = ...,
+ initial: _NumberLike_co = ...,
+ where: _ArrayLikeBool_co = ...,
+) -> _SCT | NDArray[_SCT]: ...
+@overload
+def sum(
+ a: ArrayLike,
+ axis: _ShapeLike | None = ...,
+ dtype: DTypeLike = ...,
+ out: None = ...,
+ keepdims: bool = ...,
+ initial: _NumberLike_co = ...,
+ where: _ArrayLikeBool_co = ...,
+) -> Any: ...
+@overload
+def sum(
+ a: ArrayLike,
+ axis: _ShapeLike | None,
+ dtype: DTypeLike,
+ out: _ArrayT,
+ keepdims: bool = ...,
+ initial: _NumberLike_co = ...,
+ where: _ArrayLikeBool_co = ...,
+) -> _ArrayT: ...
+@overload
+def sum(
+ a: ArrayLike,
+ axis: _ShapeLike | None = ...,
+ dtype: DTypeLike = ...,
+ *,
+ out: _ArrayT,
+ keepdims: bool = ...,
+ initial: _NumberLike_co = ...,
+ where: _ArrayLikeBool_co = ...,
+) -> _ArrayT: ...
+
+@overload
+def all(
+ a: ArrayLike,
+ axis: None = None,
+ out: None = None,
+ keepdims: Literal[False, 0] | _NoValueType = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> np.bool: ...
+@overload
+def all(
+ a: ArrayLike,
+ axis: int | tuple[int, ...] | None = None,
+ out: None = None,
+ keepdims: _BoolLike_co | _NoValueType = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> Incomplete: ...
+@overload
+def all(
+ a: ArrayLike,
+ axis: int | tuple[int, ...] | None,
+ out: _ArrayT,
+ keepdims: _BoolLike_co | _NoValueType = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> _ArrayT: ...
+@overload
+def all(
+ a: ArrayLike,
+ axis: int | tuple[int, ...] | None = None,
+ *,
+ out: _ArrayT,
+ keepdims: _BoolLike_co | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> _ArrayT: ...
+
+@overload
+def any(
+ a: ArrayLike,
+ axis: None = None,
+ out: None = None,
+ keepdims: Literal[False, 0] | _NoValueType = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> np.bool: ...
+@overload
+def any(
+ a: ArrayLike,
+ axis: int | tuple[int, ...] | None = None,
+ out: None = None,
+ keepdims: _BoolLike_co | _NoValueType = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> Incomplete: ...
+@overload
+def any(
+ a: ArrayLike,
+ axis: int | tuple[int, ...] | None,
+ out: _ArrayT,
+ keepdims: _BoolLike_co | _NoValueType = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> _ArrayT: ...
+@overload
+def any(
+ a: ArrayLike,
+ axis: int | tuple[int, ...] | None = None,
+ *,
+ out: _ArrayT,
+ keepdims: _BoolLike_co | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> _ArrayT: ...
+
+@overload
+def cumsum(
+ a: _ArrayLike[_SCT],
+ axis: SupportsIndex | None = ...,
+ dtype: None = ...,
+ out: None = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def cumsum(
+ a: ArrayLike,
+ axis: SupportsIndex | None = ...,
+ dtype: None = ...,
+ out: None = ...,
+) -> NDArray[Any]: ...
+@overload
+def cumsum(
+ a: ArrayLike,
+ axis: SupportsIndex | None,
+ dtype: _DTypeLike[_SCT],
+ out: None = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def cumsum(
+ a: ArrayLike,
+ axis: SupportsIndex | None = ...,
+ *,
+ dtype: _DTypeLike[_SCT],
+ out: None = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def cumsum(
+ a: ArrayLike,
+ axis: SupportsIndex | None = ...,
+ dtype: DTypeLike = ...,
+ out: None = ...,
+) -> NDArray[Any]: ...
+@overload
+def cumsum(
+ a: ArrayLike,
+ axis: SupportsIndex | None,
+ dtype: DTypeLike,
+ out: _ArrayT,
+) -> _ArrayT: ...
+@overload
+def cumsum(
+ a: ArrayLike,
+ axis: SupportsIndex | None = ...,
+ dtype: DTypeLike = ...,
+ *,
+ out: _ArrayT,
+) -> _ArrayT: ...
+
+@overload
+def cumulative_sum(
+ x: _ArrayLike[_SCT],
+ /,
+ *,
+ axis: SupportsIndex | None = ...,
+ dtype: None = ...,
+ out: None = ...,
+ include_initial: bool = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def cumulative_sum(
+ x: ArrayLike,
+ /,
+ *,
+ axis: SupportsIndex | None = ...,
+ dtype: None = ...,
+ out: None = ...,
+ include_initial: bool = ...,
+) -> NDArray[Any]: ...
+@overload
+def cumulative_sum(
+ x: ArrayLike,
+ /,
+ *,
+ axis: SupportsIndex | None = ...,
+ dtype: _DTypeLike[_SCT],
+ out: None = ...,
+ include_initial: bool = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def cumulative_sum(
+ x: ArrayLike,
+ /,
+ *,
+ axis: SupportsIndex | None = ...,
+ dtype: DTypeLike = ...,
+ out: None = ...,
+ include_initial: bool = ...,
+) -> NDArray[Any]: ...
+@overload
+def cumulative_sum(
+ x: ArrayLike,
+ /,
+ *,
+ axis: SupportsIndex | None = ...,
+ dtype: DTypeLike = ...,
+ out: _ArrayT,
+ include_initial: bool = ...,
+) -> _ArrayT: ...
+
+@overload
+def ptp(
+ a: _ArrayLike[_SCT],
+ axis: None = ...,
+ out: None = ...,
+ keepdims: Literal[False] = ...,
+) -> _SCT: ...
+@overload
+def ptp(
+ a: ArrayLike,
+ axis: _ShapeLike | None = ...,
+ out: None = ...,
+ keepdims: bool = ...,
+) -> Any: ...
+@overload
+def ptp(
+ a: ArrayLike,
+ axis: _ShapeLike | None,
+ out: _ArrayT,
+ keepdims: bool = ...,
+) -> _ArrayT: ...
+@overload
+def ptp(
+ a: ArrayLike,
+ axis: _ShapeLike | None = ...,
+ *,
+ out: _ArrayT,
+ keepdims: bool = ...,
+) -> _ArrayT: ...
+
+@overload
+def amax(
+ a: _ArrayLike[_SCT],
+ axis: None = ...,
+ out: None = ...,
+ keepdims: Literal[False] = ...,
+ initial: _NumberLike_co = ...,
+ where: _ArrayLikeBool_co = ...,
+) -> _SCT: ...
+@overload
+def amax(
+ a: ArrayLike,
+ axis: _ShapeLike | None = ...,
+ out: None = ...,
+ keepdims: bool = ...,
+ initial: _NumberLike_co = ...,
+ where: _ArrayLikeBool_co = ...,
+) -> Any: ...
+@overload
+def amax(
+ a: ArrayLike,
+ axis: _ShapeLike | None,
+ out: _ArrayT,
+ keepdims: bool = ...,
+ initial: _NumberLike_co = ...,
+ where: _ArrayLikeBool_co = ...,
+) -> _ArrayT: ...
+@overload
+def amax(
+ a: ArrayLike,
+ axis: _ShapeLike | None = ...,
+ *,
+ out: _ArrayT,
+ keepdims: bool = ...,
+ initial: _NumberLike_co = ...,
+ where: _ArrayLikeBool_co = ...,
+) -> _ArrayT: ...
+
+@overload
+def amin(
+ a: _ArrayLike[_SCT],
+ axis: None = ...,
+ out: None = ...,
+ keepdims: Literal[False] = ...,
+ initial: _NumberLike_co = ...,
+ where: _ArrayLikeBool_co = ...,
+) -> _SCT: ...
+@overload
+def amin(
+ a: ArrayLike,
+ axis: _ShapeLike | None = ...,
+ out: None = ...,
+ keepdims: bool = ...,
+ initial: _NumberLike_co = ...,
+ where: _ArrayLikeBool_co = ...,
+) -> Any: ...
+@overload
+def amin(
+ a: ArrayLike,
+ axis: _ShapeLike | None,
+ out: _ArrayT,
+ keepdims: bool = ...,
+ initial: _NumberLike_co = ...,
+ where: _ArrayLikeBool_co = ...,
+) -> _ArrayT: ...
+@overload
+def amin(
+ a: ArrayLike,
+ axis: _ShapeLike | None = ...,
+ *,
+ out: _ArrayT,
+ keepdims: bool = ...,
+ initial: _NumberLike_co = ...,
+ where: _ArrayLikeBool_co = ...,
+) -> _ArrayT: ...
+
+# TODO: `np.prod()``: For object arrays `initial` does not necessarily
+# have to be a numerical scalar.
+# The only requirement is that it is compatible
+# with the `.__mul__()` method(s) of the passed array's elements.
+
+# Note that the same situation holds for all wrappers around
+# `np.ufunc.reduce`, e.g. `np.sum()` (`.__add__()`).
+@overload
+def prod(
+ a: _ArrayLikeBool_co,
+ axis: None = ...,
+ dtype: None = ...,
+ out: None = ...,
+ keepdims: Literal[False] = ...,
+ initial: _NumberLike_co = ...,
+ where: _ArrayLikeBool_co = ...,
+) -> int_: ...
+@overload
+def prod(
+ a: _ArrayLikeUInt_co,
+ axis: None = ...,
+ dtype: None = ...,
+ out: None = ...,
+ keepdims: Literal[False] = ...,
+ initial: _NumberLike_co = ...,
+ where: _ArrayLikeBool_co = ...,
+) -> uint64: ...
+@overload
+def prod(
+ a: _ArrayLikeInt_co,
+ axis: None = ...,
+ dtype: None = ...,
+ out: None = ...,
+ keepdims: Literal[False] = ...,
+ initial: _NumberLike_co = ...,
+ where: _ArrayLikeBool_co = ...,
+) -> int64: ...
+@overload
+def prod(
+ a: _ArrayLikeFloat_co,
+ axis: None = ...,
+ dtype: None = ...,
+ out: None = ...,
+ keepdims: Literal[False] = ...,
+ initial: _NumberLike_co = ...,
+ where: _ArrayLikeBool_co = ...,
+) -> floating[Any]: ...
+@overload
+def prod(
+ a: _ArrayLikeComplex_co,
+ axis: None = ...,
+ dtype: None = ...,
+ out: None = ...,
+ keepdims: Literal[False] = ...,
+ initial: _NumberLike_co = ...,
+ where: _ArrayLikeBool_co = ...,
+) -> complexfloating[Any, Any]: ...
+@overload
+def prod(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: _ShapeLike | None = ...,
+ dtype: None = ...,
+ out: None = ...,
+ keepdims: bool = ...,
+ initial: _NumberLike_co = ...,
+ where: _ArrayLikeBool_co = ...,
+) -> Any: ...
+@overload
+def prod(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: None,
+ dtype: _DTypeLike[_SCT],
+ out: None = ...,
+ keepdims: Literal[False] = ...,
+ initial: _NumberLike_co = ...,
+ where: _ArrayLikeBool_co = ...,
+) -> _SCT: ...
+@overload
+def prod(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: None = ...,
+ *,
+ dtype: _DTypeLike[_SCT],
+ out: None = ...,
+ keepdims: Literal[False] = ...,
+ initial: _NumberLike_co = ...,
+ where: _ArrayLikeBool_co = ...,
+) -> _SCT: ...
+@overload
+def prod(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: _ShapeLike | None = ...,
+ dtype: DTypeLike | None = ...,
+ out: None = ...,
+ keepdims: bool = ...,
+ initial: _NumberLike_co = ...,
+ where: _ArrayLikeBool_co = ...,
+) -> Any: ...
+@overload
+def prod(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: _ShapeLike | None,
+ dtype: DTypeLike | None,
+ out: _ArrayT,
+ keepdims: bool = ...,
+ initial: _NumberLike_co = ...,
+ where: _ArrayLikeBool_co = ...,
+) -> _ArrayT: ...
+@overload
+def prod(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: _ShapeLike | None = ...,
+ dtype: DTypeLike | None = ...,
+ *,
+ out: _ArrayT,
+ keepdims: bool = ...,
+ initial: _NumberLike_co = ...,
+ where: _ArrayLikeBool_co = ...,
+) -> _ArrayT: ...
+
+@overload
+def cumprod(
+ a: _ArrayLikeBool_co,
+ axis: SupportsIndex | None = ...,
+ dtype: None = ...,
+ out: None = ...,
+) -> NDArray[int_]: ...
+@overload
+def cumprod(
+ a: _ArrayLikeUInt_co,
+ axis: SupportsIndex | None = ...,
+ dtype: None = ...,
+ out: None = ...,
+) -> NDArray[uint64]: ...
+@overload
+def cumprod(
+ a: _ArrayLikeInt_co,
+ axis: SupportsIndex | None = ...,
+ dtype: None = ...,
+ out: None = ...,
+) -> NDArray[int64]: ...
+@overload
+def cumprod(
+ a: _ArrayLikeFloat_co,
+ axis: SupportsIndex | None = ...,
+ dtype: None = ...,
+ out: None = ...,
+) -> NDArray[floating[Any]]: ...
+@overload
+def cumprod(
+ a: _ArrayLikeComplex_co,
+ axis: SupportsIndex | None = ...,
+ dtype: None = ...,
+ out: None = ...,
+) -> NDArray[complexfloating[Any, Any]]: ...
+@overload
+def cumprod(
+ a: _ArrayLikeObject_co,
+ axis: SupportsIndex | None = ...,
+ dtype: None = ...,
+ out: None = ...,
+) -> NDArray[object_]: ...
+@overload
+def cumprod(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: SupportsIndex | None,
+ dtype: _DTypeLike[_SCT],
+ out: None = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def cumprod(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: SupportsIndex | None = ...,
+ *,
+ dtype: _DTypeLike[_SCT],
+ out: None = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def cumprod(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: SupportsIndex | None = ...,
+ dtype: DTypeLike = ...,
+ out: None = ...,
+) -> NDArray[Any]: ...
+@overload
+def cumprod(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: SupportsIndex | None,
+ dtype: DTypeLike,
+ out: _ArrayT,
+) -> _ArrayT: ...
+@overload
+def cumprod(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: SupportsIndex | None = ...,
+ dtype: DTypeLike = ...,
+ *,
+ out: _ArrayT,
+) -> _ArrayT: ...
+
+@overload
+def cumulative_prod(
+ x: _ArrayLikeBool_co,
+ /,
+ *,
+ axis: SupportsIndex | None = ...,
+ dtype: None = ...,
+ out: None = ...,
+ include_initial: bool = ...,
+) -> NDArray[int_]: ...
+@overload
+def cumulative_prod(
+ x: _ArrayLikeUInt_co,
+ /,
+ *,
+ axis: SupportsIndex | None = ...,
+ dtype: None = ...,
+ out: None = ...,
+ include_initial: bool = ...,
+) -> NDArray[uint64]: ...
+@overload
+def cumulative_prod(
+ x: _ArrayLikeInt_co,
+ /,
+ *,
+ axis: SupportsIndex | None = ...,
+ dtype: None = ...,
+ out: None = ...,
+ include_initial: bool = ...,
+) -> NDArray[int64]: ...
+@overload
+def cumulative_prod(
+ x: _ArrayLikeFloat_co,
+ /,
+ *,
+ axis: SupportsIndex | None = ...,
+ dtype: None = ...,
+ out: None = ...,
+ include_initial: bool = ...,
+) -> NDArray[floating[Any]]: ...
+@overload
+def cumulative_prod(
+ x: _ArrayLikeComplex_co,
+ /,
+ *,
+ axis: SupportsIndex | None = ...,
+ dtype: None = ...,
+ out: None = ...,
+ include_initial: bool = ...,
+) -> NDArray[complexfloating[Any, Any]]: ...
+@overload
+def cumulative_prod(
+ x: _ArrayLikeObject_co,
+ /,
+ *,
+ axis: SupportsIndex | None = ...,
+ dtype: None = ...,
+ out: None = ...,
+ include_initial: bool = ...,
+) -> NDArray[object_]: ...
+@overload
+def cumulative_prod(
+ x: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ /,
+ *,
+ axis: SupportsIndex | None = ...,
+ dtype: _DTypeLike[_SCT],
+ out: None = ...,
+ include_initial: bool = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def cumulative_prod(
+ x: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ /,
+ *,
+ axis: SupportsIndex | None = ...,
+ dtype: DTypeLike = ...,
+ out: None = ...,
+ include_initial: bool = ...,
+) -> NDArray[Any]: ...
+@overload
+def cumulative_prod(
+ x: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ /,
+ *,
+ axis: SupportsIndex | None = ...,
+ dtype: DTypeLike = ...,
+ out: _ArrayT,
+ include_initial: bool = ...,
+) -> _ArrayT: ...
+
+def ndim(a: ArrayLike) -> int: ...
+
+def size(a: ArrayLike, axis: int | None = ...) -> int: ...
+
+@overload
+def around(
+ a: _BoolLike_co,
+ decimals: SupportsIndex = ...,
+ out: None = ...,
+) -> float16: ...
+@overload
+def around(
+ a: _SCT_uifcO,
+ decimals: SupportsIndex = ...,
+ out: None = ...,
+) -> _SCT_uifcO: ...
+@overload
+def around(
+ a: _ComplexLike_co | object_,
+ decimals: SupportsIndex = ...,
+ out: None = ...,
+) -> Any: ...
+@overload
+def around(
+ a: _ArrayLikeBool_co,
+ decimals: SupportsIndex = ...,
+ out: None = ...,
+) -> NDArray[float16]: ...
+@overload
+def around(
+ a: _ArrayLike[_SCT_uifcO],
+ decimals: SupportsIndex = ...,
+ out: None = ...,
+) -> NDArray[_SCT_uifcO]: ...
+@overload
+def around(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ decimals: SupportsIndex = ...,
+ out: None = ...,
+) -> NDArray[Any]: ...
+@overload
+def around(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ decimals: SupportsIndex,
+ out: _ArrayT,
+) -> _ArrayT: ...
+@overload
+def around(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ decimals: SupportsIndex = ...,
+ *,
+ out: _ArrayT,
+) -> _ArrayT: ...
+
+@overload
+def mean(
+ a: _ArrayLikeFloat_co,
+ axis: None = ...,
+ dtype: None = ...,
+ out: None = ...,
+ keepdims: Literal[False] | _NoValueType = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> floating[Any]: ...
+@overload
+def mean(
+ a: _ArrayLikeComplex_co,
+ axis: None = ...,
+ dtype: None = ...,
+ out: None = ...,
+ keepdims: Literal[False] | _NoValueType = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> complexfloating[Any]: ...
+@overload
+def mean(
+ a: _ArrayLike[np.timedelta64],
+ axis: None = ...,
+ dtype: None = ...,
+ out: None = ...,
+ keepdims: Literal[False] | _NoValueType = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> timedelta64: ...
+@overload
+def mean(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: _ShapeLike | None,
+ dtype: DTypeLike,
+ out: _ArrayT,
+ keepdims: bool | _NoValueType = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> _ArrayT: ...
+@overload
+def mean(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: _ShapeLike | None = ...,
+ dtype: DTypeLike | None = ...,
+ *,
+ out: _ArrayT,
+ keepdims: bool | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> _ArrayT: ...
+@overload
+def mean(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: None,
+ dtype: _DTypeLike[_SCT],
+ out: None = ...,
+ keepdims: Literal[False] | _NoValueType = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> _SCT: ...
+@overload
+def mean(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: None = ...,
+ *,
+ dtype: _DTypeLike[_SCT],
+ out: None = ...,
+ keepdims: Literal[False] | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> _SCT: ...
+@overload
+def mean(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: _ShapeLike | None,
+ dtype: _DTypeLike[_SCT],
+ out: None,
+ keepdims: Literal[True, 1],
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def mean(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: _ShapeLike | None,
+ dtype: _DTypeLike[_SCT],
+ out: None = ...,
+ *,
+ keepdims: bool | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> _SCT | NDArray[_SCT]: ...
+@overload
+def mean(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: _ShapeLike | None = ...,
+ *,
+ dtype: _DTypeLike[_SCT],
+ out: None = ...,
+ keepdims: bool | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> _SCT | NDArray[_SCT]: ...
+@overload
+def mean(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: _ShapeLike | None = ...,
+ dtype: DTypeLike | None = ...,
+ out: None = ...,
+ keepdims: bool | _NoValueType = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> Incomplete: ...
+
+@overload
+def std(
+ a: _ArrayLikeComplex_co,
+ axis: None = ...,
+ dtype: None = ...,
+ out: None = ...,
+ ddof: float = ...,
+ keepdims: Literal[False] = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+ mean: _ArrayLikeComplex_co | _NoValueType = ...,
+ correction: float | _NoValueType = ...,
+) -> floating[Any]: ...
+@overload
+def std(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: _ShapeLike | None = ...,
+ dtype: None = ...,
+ out: None = ...,
+ ddof: float = ...,
+ keepdims: bool = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
+ correction: float | _NoValueType = ...,
+) -> Any: ...
+@overload
+def std(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: None,
+ dtype: _DTypeLike[_SCT],
+ out: None = ...,
+ ddof: float = ...,
+ keepdims: Literal[False] = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
+ correction: float | _NoValueType = ...,
+) -> _SCT: ...
+@overload
+def std(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: None = ...,
+ *,
+ dtype: _DTypeLike[_SCT],
+ out: None = ...,
+ ddof: float = ...,
+ keepdims: Literal[False] = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
+ correction: float | _NoValueType = ...,
+) -> _SCT: ...
+@overload
+def std(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: _ShapeLike | None = ...,
+ dtype: DTypeLike = ...,
+ out: None = ...,
+ ddof: float = ...,
+ keepdims: bool = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
+ correction: float | _NoValueType = ...,
+) -> Any: ...
+@overload
+def std(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: _ShapeLike | None,
+ dtype: DTypeLike,
+ out: _ArrayT,
+ ddof: float = ...,
+ keepdims: bool = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
+ correction: float | _NoValueType = ...,
+) -> _ArrayT: ...
+@overload
+def std(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: _ShapeLike | None = ...,
+ dtype: DTypeLike = ...,
+ *,
+ out: _ArrayT,
+ ddof: float = ...,
+ keepdims: bool = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
+ correction: float | _NoValueType = ...,
+) -> _ArrayT: ...
+
+@overload
+def var(
+ a: _ArrayLikeComplex_co,
+ axis: None = ...,
+ dtype: None = ...,
+ out: None = ...,
+ ddof: float = ...,
+ keepdims: Literal[False] = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+ mean: _ArrayLikeComplex_co | _NoValueType = ...,
+ correction: float | _NoValueType = ...,
+) -> floating[Any]: ...
+@overload
+def var(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: _ShapeLike | None = ...,
+ dtype: None = ...,
+ out: None = ...,
+ ddof: float = ...,
+ keepdims: bool = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
+ correction: float | _NoValueType = ...,
+) -> Any: ...
+@overload
+def var(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: None,
+ dtype: _DTypeLike[_SCT],
+ out: None = ...,
+ ddof: float = ...,
+ keepdims: Literal[False] = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
+ correction: float | _NoValueType = ...,
+) -> _SCT: ...
+@overload
+def var(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: None = ...,
+ *,
+ dtype: _DTypeLike[_SCT],
+ out: None = ...,
+ ddof: float = ...,
+ keepdims: Literal[False] = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
+ correction: float | _NoValueType = ...,
+) -> _SCT: ...
+@overload
+def var(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: _ShapeLike | None = ...,
+ dtype: DTypeLike = ...,
+ out: None = ...,
+ ddof: float = ...,
+ keepdims: bool = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
+ correction: float | _NoValueType = ...,
+) -> Any: ...
+@overload
+def var(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: _ShapeLike | None,
+ dtype: DTypeLike,
+ out: _ArrayT,
+ ddof: float = ...,
+ keepdims: bool = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
+ correction: float | _NoValueType = ...,
+) -> _ArrayT: ...
+@overload
+def var(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: _ShapeLike | None = ...,
+ dtype: DTypeLike = ...,
+ *,
+ out: _ArrayT,
+ ddof: float = ...,
+ keepdims: bool = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
+ correction: float | _NoValueType = ...,
+) -> _ArrayT: ...
+
+max = amax
+min = amin
+round = around
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/function_base.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/function_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..cba071768ab707b088000742403d5e3b820772dc
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/function_base.py
@@ -0,0 +1,546 @@
+import functools
+import warnings
+import operator
+import types
+
+import numpy as np
+from . import numeric as _nx
+from .numeric import result_type, nan, asanyarray, ndim
+from numpy._core.multiarray import add_docstring
+from numpy._core._multiarray_umath import _array_converter
+from numpy._core import overrides
+
+__all__ = ['logspace', 'linspace', 'geomspace']
+
+
+array_function_dispatch = functools.partial(
+ overrides.array_function_dispatch, module='numpy')
+
+
+def _linspace_dispatcher(start, stop, num=None, endpoint=None, retstep=None,
+ dtype=None, axis=None, *, device=None):
+ return (start, stop)
+
+
+@array_function_dispatch(_linspace_dispatcher)
+def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None,
+ axis=0, *, device=None):
+ """
+ Return evenly spaced numbers over a specified interval.
+
+ Returns `num` evenly spaced samples, calculated over the
+ interval [`start`, `stop`].
+
+ The endpoint of the interval can optionally be excluded.
+
+ .. versionchanged:: 1.20.0
+ Values are rounded towards ``-inf`` instead of ``0`` when an
+ integer ``dtype`` is specified. The old behavior can
+ still be obtained with ``np.linspace(start, stop, num).astype(int)``
+
+ Parameters
+ ----------
+ start : array_like
+ The starting value of the sequence.
+ stop : array_like
+ The end value of the sequence, unless `endpoint` is set to False.
+ In that case, the sequence consists of all but the last of ``num + 1``
+ evenly spaced samples, so that `stop` is excluded. Note that the step
+ size changes when `endpoint` is False.
+ num : int, optional
+ Number of samples to generate. Default is 50. Must be non-negative.
+ endpoint : bool, optional
+ If True, `stop` is the last sample. Otherwise, it is not included.
+ Default is True.
+ retstep : bool, optional
+ If True, return (`samples`, `step`), where `step` is the spacing
+ between samples.
+ dtype : dtype, optional
+ The type of the output array. If `dtype` is not given, the data type
+ is inferred from `start` and `stop`. The inferred dtype will never be
+ an integer; `float` is chosen even if the arguments would produce an
+ array of integers.
+ axis : int, optional
+ The axis in the result to store the samples. Relevant only if start
+ or stop are array-like. By default (0), the samples will be along a
+ new axis inserted at the beginning. Use -1 to get an axis at the end.
+ device : str, optional
+ The device on which to place the created array. Default: None.
+ For Array-API interoperability only, so must be ``"cpu"`` if passed.
+
+ .. versionadded:: 2.0.0
+
+ Returns
+ -------
+ samples : ndarray
+ There are `num` equally spaced samples in the closed interval
+ ``[start, stop]`` or the half-open interval ``[start, stop)``
+ (depending on whether `endpoint` is True or False).
+ step : float, optional
+ Only returned if `retstep` is True
+
+ Size of spacing between samples.
+
+
+ See Also
+ --------
+ arange : Similar to `linspace`, but uses a step size (instead of the
+ number of samples).
+ geomspace : Similar to `linspace`, but with numbers spaced evenly on a log
+ scale (a geometric progression).
+ logspace : Similar to `geomspace`, but with the end points specified as
+ logarithms.
+ :ref:`how-to-partition`
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.linspace(2.0, 3.0, num=5)
+ array([2. , 2.25, 2.5 , 2.75, 3. ])
+ >>> np.linspace(2.0, 3.0, num=5, endpoint=False)
+ array([2. , 2.2, 2.4, 2.6, 2.8])
+ >>> np.linspace(2.0, 3.0, num=5, retstep=True)
+ (array([2. , 2.25, 2.5 , 2.75, 3. ]), 0.25)
+
+ Graphical illustration:
+
+ >>> import matplotlib.pyplot as plt
+ >>> N = 8
+ >>> y = np.zeros(N)
+ >>> x1 = np.linspace(0, 10, N, endpoint=True)
+ >>> x2 = np.linspace(0, 10, N, endpoint=False)
+ >>> plt.plot(x1, y, 'o')
+ []
+ >>> plt.plot(x2, y + 0.5, 'o')
+ []
+ >>> plt.ylim([-0.5, 1])
+ (-0.5, 1)
+ >>> plt.show()
+
+ """
+ num = operator.index(num)
+ if num < 0:
+ raise ValueError(
+ "Number of samples, %s, must be non-negative." % num
+ )
+ div = (num - 1) if endpoint else num
+
+ conv = _array_converter(start, stop)
+ start, stop = conv.as_arrays()
+ dt = conv.result_type(ensure_inexact=True)
+
+ if dtype is None:
+ dtype = dt
+ integer_dtype = False
+ else:
+ integer_dtype = _nx.issubdtype(dtype, _nx.integer)
+
+ # Use `dtype=type(dt)` to enforce a floating point evaluation:
+ delta = np.subtract(stop, start, dtype=type(dt))
+ y = _nx.arange(
+ 0, num, dtype=dt, device=device
+ ).reshape((-1,) + (1,) * ndim(delta))
+
+ # In-place multiplication y *= delta/div is faster, but prevents
+ # the multiplicant from overriding what class is produced, and thus
+ # prevents, e.g. use of Quantities, see gh-7142. Hence, we multiply
+ # in place only for standard scalar types.
+ if div > 0:
+ _mult_inplace = _nx.isscalar(delta)
+ step = delta / div
+ any_step_zero = (
+ step == 0 if _mult_inplace else _nx.asanyarray(step == 0).any())
+ if any_step_zero:
+ # Special handling for denormal numbers, gh-5437
+ y /= div
+ if _mult_inplace:
+ y *= delta
+ else:
+ y = y * delta
+ else:
+ if _mult_inplace:
+ y *= step
+ else:
+ y = y * step
+ else:
+ # sequences with 0 items or 1 item with endpoint=True (i.e. div <= 0)
+ # have an undefined step
+ step = nan
+ # Multiply with delta to allow possible override of output class.
+ y = y * delta
+
+ y += start
+
+ if endpoint and num > 1:
+ y[-1, ...] = stop
+
+ if axis != 0:
+ y = _nx.moveaxis(y, 0, axis)
+
+ if integer_dtype:
+ _nx.floor(y, out=y)
+
+ y = conv.wrap(y.astype(dtype, copy=False))
+ if retstep:
+ return y, step
+ else:
+ return y
+
+
+def _logspace_dispatcher(start, stop, num=None, endpoint=None, base=None,
+ dtype=None, axis=None):
+ return (start, stop, base)
+
+
+@array_function_dispatch(_logspace_dispatcher)
+def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None,
+ axis=0):
+ """
+ Return numbers spaced evenly on a log scale.
+
+ In linear space, the sequence starts at ``base ** start``
+ (`base` to the power of `start`) and ends with ``base ** stop``
+ (see `endpoint` below).
+
+ .. versionchanged:: 1.25.0
+ Non-scalar 'base` is now supported
+
+ Parameters
+ ----------
+ start : array_like
+ ``base ** start`` is the starting value of the sequence.
+ stop : array_like
+ ``base ** stop`` is the final value of the sequence, unless `endpoint`
+ is False. In that case, ``num + 1`` values are spaced over the
+ interval in log-space, of which all but the last (a sequence of
+ length `num`) are returned.
+ num : integer, optional
+ Number of samples to generate. Default is 50.
+ endpoint : boolean, optional
+ If true, `stop` is the last sample. Otherwise, it is not included.
+ Default is True.
+ base : array_like, optional
+ The base of the log space. The step size between the elements in
+ ``ln(samples) / ln(base)`` (or ``log_base(samples)``) is uniform.
+ Default is 10.0.
+ dtype : dtype
+ The type of the output array. If `dtype` is not given, the data type
+ is inferred from `start` and `stop`. The inferred type will never be
+ an integer; `float` is chosen even if the arguments would produce an
+ array of integers.
+ axis : int, optional
+ The axis in the result to store the samples. Relevant only if start,
+ stop, or base are array-like. By default (0), the samples will be
+ along a new axis inserted at the beginning. Use -1 to get an axis at
+ the end.
+
+ Returns
+ -------
+ samples : ndarray
+ `num` samples, equally spaced on a log scale.
+
+ See Also
+ --------
+ arange : Similar to linspace, with the step size specified instead of the
+ number of samples. Note that, when used with a float endpoint, the
+ endpoint may or may not be included.
+ linspace : Similar to logspace, but with the samples uniformly distributed
+ in linear space, instead of log space.
+ geomspace : Similar to logspace, but with endpoints specified directly.
+ :ref:`how-to-partition`
+
+ Notes
+ -----
+ If base is a scalar, logspace is equivalent to the code
+
+ >>> y = np.linspace(start, stop, num=num, endpoint=endpoint)
+ ... # doctest: +SKIP
+ >>> power(base, y).astype(dtype)
+ ... # doctest: +SKIP
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.logspace(2.0, 3.0, num=4)
+ array([ 100. , 215.443469 , 464.15888336, 1000. ])
+ >>> np.logspace(2.0, 3.0, num=4, endpoint=False)
+ array([100. , 177.827941 , 316.22776602, 562.34132519])
+ >>> np.logspace(2.0, 3.0, num=4, base=2.0)
+ array([4. , 5.0396842 , 6.34960421, 8. ])
+ >>> np.logspace(2.0, 3.0, num=4, base=[2.0, 3.0], axis=-1)
+ array([[ 4. , 5.0396842 , 6.34960421, 8. ],
+ [ 9. , 12.98024613, 18.72075441, 27. ]])
+
+ Graphical illustration:
+
+ >>> import matplotlib.pyplot as plt
+ >>> N = 10
+ >>> x1 = np.logspace(0.1, 1, N, endpoint=True)
+ >>> x2 = np.logspace(0.1, 1, N, endpoint=False)
+ >>> y = np.zeros(N)
+ >>> plt.plot(x1, y, 'o')
+ []
+ >>> plt.plot(x2, y + 0.5, 'o')
+ []
+ >>> plt.ylim([-0.5, 1])
+ (-0.5, 1)
+ >>> plt.show()
+
+ """
+ if not isinstance(base, (float, int)) and np.ndim(base):
+ # If base is non-scalar, broadcast it with the others, since it
+ # may influence how axis is interpreted.
+ ndmax = np.broadcast(start, stop, base).ndim
+ start, stop, base = (
+ np.array(a, copy=None, subok=True, ndmin=ndmax)
+ for a in (start, stop, base)
+ )
+ base = np.expand_dims(base, axis=axis)
+ y = linspace(start, stop, num=num, endpoint=endpoint, axis=axis)
+ if dtype is None:
+ return _nx.power(base, y)
+ return _nx.power(base, y).astype(dtype, copy=False)
+
+
+def _geomspace_dispatcher(start, stop, num=None, endpoint=None, dtype=None,
+ axis=None):
+ return (start, stop)
+
+
+@array_function_dispatch(_geomspace_dispatcher)
+def geomspace(start, stop, num=50, endpoint=True, dtype=None, axis=0):
+ """
+ Return numbers spaced evenly on a log scale (a geometric progression).
+
+ This is similar to `logspace`, but with endpoints specified directly.
+ Each output sample is a constant multiple of the previous.
+
+ Parameters
+ ----------
+ start : array_like
+ The starting value of the sequence.
+ stop : array_like
+ The final value of the sequence, unless `endpoint` is False.
+ In that case, ``num + 1`` values are spaced over the
+ interval in log-space, of which all but the last (a sequence of
+ length `num`) are returned.
+ num : integer, optional
+ Number of samples to generate. Default is 50.
+ endpoint : boolean, optional
+ If true, `stop` is the last sample. Otherwise, it is not included.
+ Default is True.
+ dtype : dtype
+ The type of the output array. If `dtype` is not given, the data type
+ is inferred from `start` and `stop`. The inferred dtype will never be
+ an integer; `float` is chosen even if the arguments would produce an
+ array of integers.
+ axis : int, optional
+ The axis in the result to store the samples. Relevant only if start
+ or stop are array-like. By default (0), the samples will be along a
+ new axis inserted at the beginning. Use -1 to get an axis at the end.
+
+ Returns
+ -------
+ samples : ndarray
+ `num` samples, equally spaced on a log scale.
+
+ See Also
+ --------
+ logspace : Similar to geomspace, but with endpoints specified using log
+ and base.
+ linspace : Similar to geomspace, but with arithmetic instead of geometric
+ progression.
+ arange : Similar to linspace, with the step size specified instead of the
+ number of samples.
+ :ref:`how-to-partition`
+
+ Notes
+ -----
+ If the inputs or dtype are complex, the output will follow a logarithmic
+ spiral in the complex plane. (There are an infinite number of spirals
+ passing through two points; the output will follow the shortest such path.)
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.geomspace(1, 1000, num=4)
+ array([ 1., 10., 100., 1000.])
+ >>> np.geomspace(1, 1000, num=3, endpoint=False)
+ array([ 1., 10., 100.])
+ >>> np.geomspace(1, 1000, num=4, endpoint=False)
+ array([ 1. , 5.62341325, 31.6227766 , 177.827941 ])
+ >>> np.geomspace(1, 256, num=9)
+ array([ 1., 2., 4., 8., 16., 32., 64., 128., 256.])
+
+ Note that the above may not produce exact integers:
+
+ >>> np.geomspace(1, 256, num=9, dtype=int)
+ array([ 1, 2, 4, 7, 16, 32, 63, 127, 256])
+ >>> np.around(np.geomspace(1, 256, num=9)).astype(int)
+ array([ 1, 2, 4, 8, 16, 32, 64, 128, 256])
+
+ Negative, decreasing, and complex inputs are allowed:
+
+ >>> np.geomspace(1000, 1, num=4)
+ array([1000., 100., 10., 1.])
+ >>> np.geomspace(-1000, -1, num=4)
+ array([-1000., -100., -10., -1.])
+ >>> np.geomspace(1j, 1000j, num=4) # Straight line
+ array([0. +1.j, 0. +10.j, 0. +100.j, 0.+1000.j])
+ >>> np.geomspace(-1+0j, 1+0j, num=5) # Circle
+ array([-1.00000000e+00+1.22464680e-16j, -7.07106781e-01+7.07106781e-01j,
+ 6.12323400e-17+1.00000000e+00j, 7.07106781e-01+7.07106781e-01j,
+ 1.00000000e+00+0.00000000e+00j])
+
+ Graphical illustration of `endpoint` parameter:
+
+ >>> import matplotlib.pyplot as plt
+ >>> N = 10
+ >>> y = np.zeros(N)
+ >>> plt.semilogx(np.geomspace(1, 1000, N, endpoint=True), y + 1, 'o')
+ []
+ >>> plt.semilogx(np.geomspace(1, 1000, N, endpoint=False), y + 2, 'o')
+ []
+ >>> plt.axis([0.5, 2000, 0, 3])
+ [0.5, 2000, 0, 3]
+ >>> plt.grid(True, color='0.7', linestyle='-', which='both', axis='both')
+ >>> plt.show()
+
+ """
+ start = asanyarray(start)
+ stop = asanyarray(stop)
+ if _nx.any(start == 0) or _nx.any(stop == 0):
+ raise ValueError('Geometric sequence cannot include zero')
+
+ dt = result_type(start, stop, float(num), _nx.zeros((), dtype))
+ if dtype is None:
+ dtype = dt
+ else:
+ # complex to dtype('complex128'), for instance
+ dtype = _nx.dtype(dtype)
+
+ # Promote both arguments to the same dtype in case, for instance, one is
+ # complex and another is negative and log would produce NaN otherwise.
+ # Copy since we may change things in-place further down.
+ start = start.astype(dt, copy=True)
+ stop = stop.astype(dt, copy=True)
+
+ # Allow negative real values and ensure a consistent result for complex
+ # (including avoiding negligible real or imaginary parts in output) by
+ # rotating start to positive real, calculating, then undoing rotation.
+ out_sign = _nx.sign(start)
+ start /= out_sign
+ stop = stop / out_sign
+
+ log_start = _nx.log10(start)
+ log_stop = _nx.log10(stop)
+ result = logspace(log_start, log_stop, num=num,
+ endpoint=endpoint, base=10.0, dtype=dt)
+
+ # Make sure the endpoints match the start and stop arguments. This is
+ # necessary because np.exp(np.log(x)) is not necessarily equal to x.
+ if num > 0:
+ result[0] = start
+ if num > 1 and endpoint:
+ result[-1] = stop
+
+ result *= out_sign
+
+ if axis != 0:
+ result = _nx.moveaxis(result, 0, axis)
+
+ return result.astype(dtype, copy=False)
+
+
+def _needs_add_docstring(obj):
+ """
+ Returns true if the only way to set the docstring of `obj` from python is
+ via add_docstring.
+
+ This function errs on the side of being overly conservative.
+ """
+ Py_TPFLAGS_HEAPTYPE = 1 << 9
+
+ if isinstance(obj, (types.FunctionType, types.MethodType, property)):
+ return False
+
+ if isinstance(obj, type) and obj.__flags__ & Py_TPFLAGS_HEAPTYPE:
+ return False
+
+ return True
+
+
+def _add_docstring(obj, doc, warn_on_python):
+ if warn_on_python and not _needs_add_docstring(obj):
+ warnings.warn(
+ "add_newdoc was used on a pure-python object {}. "
+ "Prefer to attach it directly to the source."
+ .format(obj),
+ UserWarning,
+ stacklevel=3)
+ try:
+ add_docstring(obj, doc)
+ except Exception:
+ pass
+
+
+def add_newdoc(place, obj, doc, warn_on_python=True):
+ """
+ Add documentation to an existing object, typically one defined in C
+
+ The purpose is to allow easier editing of the docstrings without requiring
+ a re-compile. This exists primarily for internal use within numpy itself.
+
+ Parameters
+ ----------
+ place : str
+ The absolute name of the module to import from
+ obj : str or None
+ The name of the object to add documentation to, typically a class or
+ function name.
+ doc : {str, Tuple[str, str], List[Tuple[str, str]]}
+ If a string, the documentation to apply to `obj`
+
+ If a tuple, then the first element is interpreted as an attribute
+ of `obj` and the second as the docstring to apply -
+ ``(method, docstring)``
+
+ If a list, then each element of the list should be a tuple of length
+ two - ``[(method1, docstring1), (method2, docstring2), ...]``
+ warn_on_python : bool
+ If True, the default, emit `UserWarning` if this is used to attach
+ documentation to a pure-python object.
+
+ Notes
+ -----
+ This routine never raises an error if the docstring can't be written, but
+ will raise an error if the object being documented does not exist.
+
+ This routine cannot modify read-only docstrings, as appear
+ in new-style classes or built-in functions. Because this
+ routine never raises an error the caller must check manually
+ that the docstrings were changed.
+
+ Since this function grabs the ``char *`` from a c-level str object and puts
+ it into the ``tp_doc`` slot of the type of `obj`, it violates a number of
+ C-API best-practices, by:
+
+ - modifying a `PyTypeObject` after calling `PyType_Ready`
+ - calling `Py_INCREF` on the str and losing the reference, so the str
+ will never be released
+
+ If possible it should be avoided.
+ """
+ new = getattr(__import__(place, globals(), {}, [obj]), obj)
+ if isinstance(doc, str):
+ if "${ARRAY_FUNCTION_LIKE}" in doc:
+ doc = overrides.get_array_function_like_doc(new, doc)
+ _add_docstring(new, doc.strip(), warn_on_python)
+ elif isinstance(doc, tuple):
+ attr, docstring = doc
+ _add_docstring(getattr(new, attr), docstring.strip(), warn_on_python)
+ elif isinstance(doc, list):
+ for attr, docstring in doc:
+ _add_docstring(
+ getattr(new, attr), docstring.strip(), warn_on_python
+ )
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/function_base.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/function_base.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..12fdf677d0f5ff604ee9aca5d38c602ca79b295e
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/function_base.pyi
@@ -0,0 +1,235 @@
+from typing import (
+ Literal as L,
+ overload,
+ Any,
+ SupportsIndex,
+ TypeVar,
+)
+
+from numpy import floating, complexfloating, generic
+from numpy._typing import (
+ NDArray,
+ DTypeLike,
+ _DTypeLike,
+ _ArrayLikeFloat_co,
+ _ArrayLikeComplex_co,
+)
+
+__all__ = ["logspace", "linspace", "geomspace"]
+
+_SCT = TypeVar("_SCT", bound=generic)
+
+@overload
+def linspace(
+ start: _ArrayLikeFloat_co,
+ stop: _ArrayLikeFloat_co,
+ num: SupportsIndex = ...,
+ endpoint: bool = ...,
+ retstep: L[False] = ...,
+ dtype: None = ...,
+ axis: SupportsIndex = ...,
+ *,
+ device: L["cpu"] | None = ...,
+) -> NDArray[floating]: ...
+@overload
+def linspace(
+ start: _ArrayLikeComplex_co,
+ stop: _ArrayLikeComplex_co,
+ num: SupportsIndex = ...,
+ endpoint: bool = ...,
+ retstep: L[False] = ...,
+ dtype: None = ...,
+ axis: SupportsIndex = ...,
+ *,
+ device: L["cpu"] | None = ...,
+) -> NDArray[complexfloating]: ...
+@overload
+def linspace(
+ start: _ArrayLikeComplex_co,
+ stop: _ArrayLikeComplex_co,
+ num: SupportsIndex,
+ endpoint: bool,
+ retstep: L[False],
+ dtype: _DTypeLike[_SCT],
+ axis: SupportsIndex = ...,
+ *,
+ device: L["cpu"] | None = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def linspace(
+ start: _ArrayLikeComplex_co,
+ stop: _ArrayLikeComplex_co,
+ num: SupportsIndex = ...,
+ endpoint: bool = ...,
+ retstep: L[False] = ...,
+ *,
+ dtype: _DTypeLike[_SCT],
+ axis: SupportsIndex = ...,
+ device: L["cpu"] | None = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def linspace(
+ start: _ArrayLikeComplex_co,
+ stop: _ArrayLikeComplex_co,
+ num: SupportsIndex = ...,
+ endpoint: bool = ...,
+ retstep: L[False] = ...,
+ dtype: DTypeLike = ...,
+ axis: SupportsIndex = ...,
+ *,
+ device: L["cpu"] | None = ...,
+) -> NDArray[Any]: ...
+@overload
+def linspace(
+ start: _ArrayLikeFloat_co,
+ stop: _ArrayLikeFloat_co,
+ num: SupportsIndex = ...,
+ endpoint: bool = ...,
+ *,
+ retstep: L[True],
+ dtype: None = ...,
+ axis: SupportsIndex = ...,
+ device: L["cpu"] | None = ...,
+) -> tuple[NDArray[floating], floating]: ...
+@overload
+def linspace(
+ start: _ArrayLikeComplex_co,
+ stop: _ArrayLikeComplex_co,
+ num: SupportsIndex = ...,
+ endpoint: bool = ...,
+ *,
+ retstep: L[True],
+ dtype: None = ...,
+ axis: SupportsIndex = ...,
+ device: L["cpu"] | None = ...,
+) -> tuple[NDArray[complexfloating], complexfloating]: ...
+@overload
+def linspace(
+ start: _ArrayLikeComplex_co,
+ stop: _ArrayLikeComplex_co,
+ num: SupportsIndex = ...,
+ endpoint: bool = ...,
+ *,
+ retstep: L[True],
+ dtype: _DTypeLike[_SCT],
+ axis: SupportsIndex = ...,
+ device: L["cpu"] | None = ...,
+) -> tuple[NDArray[_SCT], _SCT]: ...
+@overload
+def linspace(
+ start: _ArrayLikeComplex_co,
+ stop: _ArrayLikeComplex_co,
+ num: SupportsIndex = ...,
+ endpoint: bool = ...,
+ *,
+ retstep: L[True],
+ dtype: DTypeLike = ...,
+ axis: SupportsIndex = ...,
+ device: L["cpu"] | None = ...,
+) -> tuple[NDArray[Any], Any]: ...
+
+@overload
+def logspace(
+ start: _ArrayLikeFloat_co,
+ stop: _ArrayLikeFloat_co,
+ num: SupportsIndex = ...,
+ endpoint: bool = ...,
+ base: _ArrayLikeFloat_co = ...,
+ dtype: None = ...,
+ axis: SupportsIndex = ...,
+) -> NDArray[floating]: ...
+@overload
+def logspace(
+ start: _ArrayLikeComplex_co,
+ stop: _ArrayLikeComplex_co,
+ num: SupportsIndex = ...,
+ endpoint: bool = ...,
+ base: _ArrayLikeComplex_co = ...,
+ dtype: None = ...,
+ axis: SupportsIndex = ...,
+) -> NDArray[complexfloating]: ...
+@overload
+def logspace(
+ start: _ArrayLikeComplex_co,
+ stop: _ArrayLikeComplex_co,
+ num: SupportsIndex,
+ endpoint: bool,
+ base: _ArrayLikeComplex_co,
+ dtype: _DTypeLike[_SCT],
+ axis: SupportsIndex = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def logspace(
+ start: _ArrayLikeComplex_co,
+ stop: _ArrayLikeComplex_co,
+ num: SupportsIndex = ...,
+ endpoint: bool = ...,
+ base: _ArrayLikeComplex_co = ...,
+ *,
+ dtype: _DTypeLike[_SCT],
+ axis: SupportsIndex = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def logspace(
+ start: _ArrayLikeComplex_co,
+ stop: _ArrayLikeComplex_co,
+ num: SupportsIndex = ...,
+ endpoint: bool = ...,
+ base: _ArrayLikeComplex_co = ...,
+ dtype: DTypeLike = ...,
+ axis: SupportsIndex = ...,
+) -> NDArray[Any]: ...
+
+@overload
+def geomspace(
+ start: _ArrayLikeFloat_co,
+ stop: _ArrayLikeFloat_co,
+ num: SupportsIndex = ...,
+ endpoint: bool = ...,
+ dtype: None = ...,
+ axis: SupportsIndex = ...,
+) -> NDArray[floating]: ...
+@overload
+def geomspace(
+ start: _ArrayLikeComplex_co,
+ stop: _ArrayLikeComplex_co,
+ num: SupportsIndex = ...,
+ endpoint: bool = ...,
+ dtype: None = ...,
+ axis: SupportsIndex = ...,
+) -> NDArray[complexfloating]: ...
+@overload
+def geomspace(
+ start: _ArrayLikeComplex_co,
+ stop: _ArrayLikeComplex_co,
+ num: SupportsIndex,
+ endpoint: bool,
+ dtype: _DTypeLike[_SCT],
+ axis: SupportsIndex = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def geomspace(
+ start: _ArrayLikeComplex_co,
+ stop: _ArrayLikeComplex_co,
+ num: SupportsIndex = ...,
+ endpoint: bool = ...,
+ *,
+ dtype: _DTypeLike[_SCT],
+ axis: SupportsIndex = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def geomspace(
+ start: _ArrayLikeComplex_co,
+ stop: _ArrayLikeComplex_co,
+ num: SupportsIndex = ...,
+ endpoint: bool = ...,
+ dtype: DTypeLike = ...,
+ axis: SupportsIndex = ...,
+) -> NDArray[Any]: ...
+
+def add_newdoc(
+ place: str,
+ obj: str,
+ doc: str | tuple[str, str] | list[tuple[str, str]],
+ warn_on_python: bool = ...,
+) -> None: ...
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/getlimits.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/getlimits.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ceb8139ee70582cb0865da7801b51b01293e5a7
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/getlimits.py
@@ -0,0 +1,747 @@
+"""Machine limits for Float32 and Float64 and (long double) if available...
+
+"""
+__all__ = ['finfo', 'iinfo']
+
+import types
+import warnings
+
+from .._utils import set_module
+from ._machar import MachAr
+from . import numeric
+from . import numerictypes as ntypes
+from .numeric import array, inf, nan
+from .umath import log10, exp2, nextafter, isnan
+
+
+def _fr0(a):
+ """fix rank-0 --> rank-1"""
+ if a.ndim == 0:
+ a = a.copy()
+ a.shape = (1,)
+ return a
+
+
+def _fr1(a):
+ """fix rank > 0 --> rank-0"""
+ if a.size == 1:
+ a = a.copy()
+ a.shape = ()
+ return a
+
+
+class MachArLike:
+ """ Object to simulate MachAr instance """
+ def __init__(self, ftype, *, eps, epsneg, huge, tiny,
+ ibeta, smallest_subnormal=None, **kwargs):
+ self.params = _MACHAR_PARAMS[ftype]
+ self.ftype = ftype
+ self.title = self.params['title']
+ # Parameter types same as for discovered MachAr object.
+ if not smallest_subnormal:
+ self._smallest_subnormal = nextafter(
+ self.ftype(0), self.ftype(1), dtype=self.ftype)
+ else:
+ self._smallest_subnormal = smallest_subnormal
+ self.epsilon = self.eps = self._float_to_float(eps)
+ self.epsneg = self._float_to_float(epsneg)
+ self.xmax = self.huge = self._float_to_float(huge)
+ self.xmin = self._float_to_float(tiny)
+ self.smallest_normal = self.tiny = self._float_to_float(tiny)
+ self.ibeta = self.params['itype'](ibeta)
+ self.__dict__.update(kwargs)
+ self.precision = int(-log10(self.eps))
+ self.resolution = self._float_to_float(
+ self._float_conv(10) ** (-self.precision))
+ self._str_eps = self._float_to_str(self.eps)
+ self._str_epsneg = self._float_to_str(self.epsneg)
+ self._str_xmin = self._float_to_str(self.xmin)
+ self._str_xmax = self._float_to_str(self.xmax)
+ self._str_resolution = self._float_to_str(self.resolution)
+ self._str_smallest_normal = self._float_to_str(self.xmin)
+
+ @property
+ def smallest_subnormal(self):
+ """Return the value for the smallest subnormal.
+
+ Returns
+ -------
+ smallest_subnormal : float
+ value for the smallest subnormal.
+
+ Warns
+ -----
+ UserWarning
+ If the calculated value for the smallest subnormal is zero.
+ """
+ # Check that the calculated value is not zero, in case it raises a
+ # warning.
+ value = self._smallest_subnormal
+ if self.ftype(0) == value:
+ warnings.warn(
+ 'The value of the smallest subnormal for {} type '
+ 'is zero.'.format(self.ftype), UserWarning, stacklevel=2)
+
+ return self._float_to_float(value)
+
+ @property
+ def _str_smallest_subnormal(self):
+ """Return the string representation of the smallest subnormal."""
+ return self._float_to_str(self.smallest_subnormal)
+
+ def _float_to_float(self, value):
+ """Converts float to float.
+
+ Parameters
+ ----------
+ value : float
+ value to be converted.
+ """
+ return _fr1(self._float_conv(value))
+
+ def _float_conv(self, value):
+ """Converts float to conv.
+
+ Parameters
+ ----------
+ value : float
+ value to be converted.
+ """
+ return array([value], self.ftype)
+
+ def _float_to_str(self, value):
+ """Converts float to str.
+
+ Parameters
+ ----------
+ value : float
+ value to be converted.
+ """
+ return self.params['fmt'] % array(_fr0(value)[0], self.ftype)
+
+
+_convert_to_float = {
+ ntypes.csingle: ntypes.single,
+ ntypes.complex128: ntypes.float64,
+ ntypes.clongdouble: ntypes.longdouble
+ }
+
+# Parameters for creating MachAr / MachAr-like objects
+_title_fmt = 'numpy {} precision floating point number'
+_MACHAR_PARAMS = {
+ ntypes.double: dict(
+ itype = ntypes.int64,
+ fmt = '%24.16e',
+ title = _title_fmt.format('double')),
+ ntypes.single: dict(
+ itype = ntypes.int32,
+ fmt = '%15.7e',
+ title = _title_fmt.format('single')),
+ ntypes.longdouble: dict(
+ itype = ntypes.longlong,
+ fmt = '%s',
+ title = _title_fmt.format('long double')),
+ ntypes.half: dict(
+ itype = ntypes.int16,
+ fmt = '%12.5e',
+ title = _title_fmt.format('half'))}
+
+# Key to identify the floating point type. Key is result of
+#
+# ftype = np.longdouble # or float64, float32, etc.
+# v = (ftype(-1.0) / ftype(10.0))
+# v.view(v.dtype.newbyteorder('<')).tobytes()
+#
+# Uses division to work around deficiencies in strtold on some platforms.
+# See:
+# https://perl5.git.perl.org/perl.git/blob/3118d7d684b56cbeb702af874f4326683c45f045:/Configure
+
+_KNOWN_TYPES = {}
+def _register_type(machar, bytepat):
+ _KNOWN_TYPES[bytepat] = machar
+
+
+_float_ma = {}
+
+
+def _register_known_types():
+ # Known parameters for float16
+ # See docstring of MachAr class for description of parameters.
+ f16 = ntypes.float16
+ float16_ma = MachArLike(f16,
+ machep=-10,
+ negep=-11,
+ minexp=-14,
+ maxexp=16,
+ it=10,
+ iexp=5,
+ ibeta=2,
+ irnd=5,
+ ngrd=0,
+ eps=exp2(f16(-10)),
+ epsneg=exp2(f16(-11)),
+ huge=f16(65504),
+ tiny=f16(2 ** -14))
+ _register_type(float16_ma, b'f\xae')
+ _float_ma[16] = float16_ma
+
+ # Known parameters for float32
+ f32 = ntypes.float32
+ float32_ma = MachArLike(f32,
+ machep=-23,
+ negep=-24,
+ minexp=-126,
+ maxexp=128,
+ it=23,
+ iexp=8,
+ ibeta=2,
+ irnd=5,
+ ngrd=0,
+ eps=exp2(f32(-23)),
+ epsneg=exp2(f32(-24)),
+ huge=f32((1 - 2 ** -24) * 2**128),
+ tiny=exp2(f32(-126)))
+ _register_type(float32_ma, b'\xcd\xcc\xcc\xbd')
+ _float_ma[32] = float32_ma
+
+ # Known parameters for float64
+ f64 = ntypes.float64
+ epsneg_f64 = 2.0 ** -53.0
+ tiny_f64 = 2.0 ** -1022.0
+ float64_ma = MachArLike(f64,
+ machep=-52,
+ negep=-53,
+ minexp=-1022,
+ maxexp=1024,
+ it=52,
+ iexp=11,
+ ibeta=2,
+ irnd=5,
+ ngrd=0,
+ eps=2.0 ** -52.0,
+ epsneg=epsneg_f64,
+ huge=(1.0 - epsneg_f64) / tiny_f64 * f64(4),
+ tiny=tiny_f64)
+ _register_type(float64_ma, b'\x9a\x99\x99\x99\x99\x99\xb9\xbf')
+ _float_ma[64] = float64_ma
+
+ # Known parameters for IEEE 754 128-bit binary float
+ ld = ntypes.longdouble
+ epsneg_f128 = exp2(ld(-113))
+ tiny_f128 = exp2(ld(-16382))
+ # Ignore runtime error when this is not f128
+ with numeric.errstate(all='ignore'):
+ huge_f128 = (ld(1) - epsneg_f128) / tiny_f128 * ld(4)
+ float128_ma = MachArLike(ld,
+ machep=-112,
+ negep=-113,
+ minexp=-16382,
+ maxexp=16384,
+ it=112,
+ iexp=15,
+ ibeta=2,
+ irnd=5,
+ ngrd=0,
+ eps=exp2(ld(-112)),
+ epsneg=epsneg_f128,
+ huge=huge_f128,
+ tiny=tiny_f128)
+ # IEEE 754 128-bit binary float
+ _register_type(float128_ma,
+ b'\x9a\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\xfb\xbf')
+ _float_ma[128] = float128_ma
+
+ # Known parameters for float80 (Intel 80-bit extended precision)
+ epsneg_f80 = exp2(ld(-64))
+ tiny_f80 = exp2(ld(-16382))
+ # Ignore runtime error when this is not f80
+ with numeric.errstate(all='ignore'):
+ huge_f80 = (ld(1) - epsneg_f80) / tiny_f80 * ld(4)
+ float80_ma = MachArLike(ld,
+ machep=-63,
+ negep=-64,
+ minexp=-16382,
+ maxexp=16384,
+ it=63,
+ iexp=15,
+ ibeta=2,
+ irnd=5,
+ ngrd=0,
+ eps=exp2(ld(-63)),
+ epsneg=epsneg_f80,
+ huge=huge_f80,
+ tiny=tiny_f80)
+ # float80, first 10 bytes containing actual storage
+ _register_type(float80_ma, b'\xcd\xcc\xcc\xcc\xcc\xcc\xcc\xcc\xfb\xbf')
+ _float_ma[80] = float80_ma
+
+ # Guessed / known parameters for double double; see:
+ # https://en.wikipedia.org/wiki/Quadruple-precision_floating-point_format#Double-double_arithmetic
+ # These numbers have the same exponent range as float64, but extended
+ # number of digits in the significand.
+ huge_dd = nextafter(ld(inf), ld(0), dtype=ld)
+ # As the smallest_normal in double double is so hard to calculate we set
+ # it to NaN.
+ smallest_normal_dd = nan
+ # Leave the same value for the smallest subnormal as double
+ smallest_subnormal_dd = ld(nextafter(0., 1.))
+ float_dd_ma = MachArLike(ld,
+ machep=-105,
+ negep=-106,
+ minexp=-1022,
+ maxexp=1024,
+ it=105,
+ iexp=11,
+ ibeta=2,
+ irnd=5,
+ ngrd=0,
+ eps=exp2(ld(-105)),
+ epsneg=exp2(ld(-106)),
+ huge=huge_dd,
+ tiny=smallest_normal_dd,
+ smallest_subnormal=smallest_subnormal_dd)
+ # double double; low, high order (e.g. PPC 64)
+ _register_type(float_dd_ma,
+ b'\x9a\x99\x99\x99\x99\x99Y<\x9a\x99\x99\x99\x99\x99\xb9\xbf')
+ # double double; high, low order (e.g. PPC 64 le)
+ _register_type(float_dd_ma,
+ b'\x9a\x99\x99\x99\x99\x99\xb9\xbf\x9a\x99\x99\x99\x99\x99Y<')
+ _float_ma['dd'] = float_dd_ma
+
+
+def _get_machar(ftype):
+ """ Get MachAr instance or MachAr-like instance
+
+ Get parameters for floating point type, by first trying signatures of
+ various known floating point types, then, if none match, attempting to
+ identify parameters by analysis.
+
+ Parameters
+ ----------
+ ftype : class
+ Numpy floating point type class (e.g. ``np.float64``)
+
+ Returns
+ -------
+ ma_like : instance of :class:`MachAr` or :class:`MachArLike`
+ Object giving floating point parameters for `ftype`.
+
+ Warns
+ -----
+ UserWarning
+ If the binary signature of the float type is not in the dictionary of
+ known float types.
+ """
+ params = _MACHAR_PARAMS.get(ftype)
+ if params is None:
+ raise ValueError(repr(ftype))
+ # Detect known / suspected types
+ # ftype(-1.0) / ftype(10.0) is better than ftype('-0.1') because stold
+ # may be deficient
+ key = (ftype(-1.0) / ftype(10.))
+ key = key.view(key.dtype.newbyteorder("<")).tobytes()
+ ma_like = None
+ if ftype == ntypes.longdouble:
+ # Could be 80 bit == 10 byte extended precision, where last bytes can
+ # be random garbage.
+ # Comparing first 10 bytes to pattern first to avoid branching on the
+ # random garbage.
+ ma_like = _KNOWN_TYPES.get(key[:10])
+ if ma_like is None:
+ # see if the full key is known.
+ ma_like = _KNOWN_TYPES.get(key)
+ if ma_like is None and len(key) == 16:
+ # machine limits could be f80 masquerading as np.float128,
+ # find all keys with length 16 and make new dict, but make the keys
+ # only 10 bytes long, the last bytes can be random garbage
+ _kt = {k[:10]: v for k, v in _KNOWN_TYPES.items() if len(k) == 16}
+ ma_like = _kt.get(key[:10])
+ if ma_like is not None:
+ return ma_like
+ # Fall back to parameter discovery
+ warnings.warn(
+ f'Signature {key} for {ftype} does not match any known type: '
+ 'falling back to type probe function.\n'
+ 'This warnings indicates broken support for the dtype!',
+ UserWarning, stacklevel=2)
+ return _discovered_machar(ftype)
+
+
+def _discovered_machar(ftype):
+ """ Create MachAr instance with found information on float types
+
+ TODO: MachAr should be retired completely ideally. We currently only
+ ever use it system with broken longdouble (valgrind, WSL).
+ """
+ params = _MACHAR_PARAMS[ftype]
+ return MachAr(lambda v: array([v], ftype),
+ lambda v: _fr0(v.astype(params['itype']))[0],
+ lambda v: array(_fr0(v)[0], ftype),
+ lambda v: params['fmt'] % array(_fr0(v)[0], ftype),
+ params['title'])
+
+
+@set_module('numpy')
+class finfo:
+ """
+ finfo(dtype)
+
+ Machine limits for floating point types.
+
+ Attributes
+ ----------
+ bits : int
+ The number of bits occupied by the type.
+ dtype : dtype
+ Returns the dtype for which `finfo` returns information. For complex
+ input, the returned dtype is the associated ``float*`` dtype for its
+ real and complex components.
+ eps : float
+ The difference between 1.0 and the next smallest representable float
+ larger than 1.0. For example, for 64-bit binary floats in the IEEE-754
+ standard, ``eps = 2**-52``, approximately 2.22e-16.
+ epsneg : float
+ The difference between 1.0 and the next smallest representable float
+ less than 1.0. For example, for 64-bit binary floats in the IEEE-754
+ standard, ``epsneg = 2**-53``, approximately 1.11e-16.
+ iexp : int
+ The number of bits in the exponent portion of the floating point
+ representation.
+ machep : int
+ The exponent that yields `eps`.
+ max : floating point number of the appropriate type
+ The largest representable number.
+ maxexp : int
+ The smallest positive power of the base (2) that causes overflow.
+ min : floating point number of the appropriate type
+ The smallest representable number, typically ``-max``.
+ minexp : int
+ The most negative power of the base (2) consistent with there
+ being no leading 0's in the mantissa.
+ negep : int
+ The exponent that yields `epsneg`.
+ nexp : int
+ The number of bits in the exponent including its sign and bias.
+ nmant : int
+ The number of bits in the mantissa.
+ precision : int
+ The approximate number of decimal digits to which this kind of
+ float is precise.
+ resolution : floating point number of the appropriate type
+ The approximate decimal resolution of this type, i.e.,
+ ``10**-precision``.
+ tiny : float
+ An alias for `smallest_normal`, kept for backwards compatibility.
+ smallest_normal : float
+ The smallest positive floating point number with 1 as leading bit in
+ the mantissa following IEEE-754 (see Notes).
+ smallest_subnormal : float
+ The smallest positive floating point number with 0 as leading bit in
+ the mantissa following IEEE-754.
+
+ Parameters
+ ----------
+ dtype : float, dtype, or instance
+ Kind of floating point or complex floating point
+ data-type about which to get information.
+
+ See Also
+ --------
+ iinfo : The equivalent for integer data types.
+ spacing : The distance between a value and the nearest adjacent number
+ nextafter : The next floating point value after x1 towards x2
+
+ Notes
+ -----
+ For developers of NumPy: do not instantiate this at the module level.
+ The initial calculation of these parameters is expensive and negatively
+ impacts import times. These objects are cached, so calling ``finfo()``
+ repeatedly inside your functions is not a problem.
+
+ Note that ``smallest_normal`` is not actually the smallest positive
+ representable value in a NumPy floating point type. As in the IEEE-754
+ standard [1]_, NumPy floating point types make use of subnormal numbers to
+ fill the gap between 0 and ``smallest_normal``. However, subnormal numbers
+ may have significantly reduced precision [2]_.
+
+ This function can also be used for complex data types as well. If used,
+ the output will be the same as the corresponding real float type
+ (e.g. numpy.finfo(numpy.csingle) is the same as numpy.finfo(numpy.single)).
+ However, the output is true for the real and imaginary components.
+
+ References
+ ----------
+ .. [1] IEEE Standard for Floating-Point Arithmetic, IEEE Std 754-2008,
+ pp.1-70, 2008, https://doi.org/10.1109/IEEESTD.2008.4610935
+ .. [2] Wikipedia, "Denormal Numbers",
+ https://en.wikipedia.org/wiki/Denormal_number
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.finfo(np.float64).dtype
+ dtype('float64')
+ >>> np.finfo(np.complex64).dtype
+ dtype('float32')
+
+ """
+
+ _finfo_cache = {}
+
+ __class_getitem__ = classmethod(types.GenericAlias)
+
+ def __new__(cls, dtype):
+ try:
+ obj = cls._finfo_cache.get(dtype) # most common path
+ if obj is not None:
+ return obj
+ except TypeError:
+ pass
+
+ if dtype is None:
+ # Deprecated in NumPy 1.25, 2023-01-16
+ warnings.warn(
+ "finfo() dtype cannot be None. This behavior will "
+ "raise an error in the future. (Deprecated in NumPy 1.25)",
+ DeprecationWarning,
+ stacklevel=2
+ )
+
+ try:
+ dtype = numeric.dtype(dtype)
+ except TypeError:
+ # In case a float instance was given
+ dtype = numeric.dtype(type(dtype))
+
+ obj = cls._finfo_cache.get(dtype)
+ if obj is not None:
+ return obj
+ dtypes = [dtype]
+ newdtype = ntypes.obj2sctype(dtype)
+ if newdtype is not dtype:
+ dtypes.append(newdtype)
+ dtype = newdtype
+ if not issubclass(dtype, numeric.inexact):
+ raise ValueError("data type %r not inexact" % (dtype))
+ obj = cls._finfo_cache.get(dtype)
+ if obj is not None:
+ return obj
+ if not issubclass(dtype, numeric.floating):
+ newdtype = _convert_to_float[dtype]
+ if newdtype is not dtype:
+ # dtype changed, for example from complex128 to float64
+ dtypes.append(newdtype)
+ dtype = newdtype
+
+ obj = cls._finfo_cache.get(dtype, None)
+ if obj is not None:
+ # the original dtype was not in the cache, but the new
+ # dtype is in the cache. we add the original dtypes to
+ # the cache and return the result
+ for dt in dtypes:
+ cls._finfo_cache[dt] = obj
+ return obj
+ obj = object.__new__(cls)._init(dtype)
+ for dt in dtypes:
+ cls._finfo_cache[dt] = obj
+ return obj
+
+ def _init(self, dtype):
+ self.dtype = numeric.dtype(dtype)
+ machar = _get_machar(dtype)
+
+ for word in ['precision', 'iexp',
+ 'maxexp', 'minexp', 'negep',
+ 'machep']:
+ setattr(self, word, getattr(machar, word))
+ for word in ['resolution', 'epsneg', 'smallest_subnormal']:
+ setattr(self, word, getattr(machar, word).flat[0])
+ self.bits = self.dtype.itemsize * 8
+ self.max = machar.huge.flat[0]
+ self.min = -self.max
+ self.eps = machar.eps.flat[0]
+ self.nexp = machar.iexp
+ self.nmant = machar.it
+ self._machar = machar
+ self._str_tiny = machar._str_xmin.strip()
+ self._str_max = machar._str_xmax.strip()
+ self._str_epsneg = machar._str_epsneg.strip()
+ self._str_eps = machar._str_eps.strip()
+ self._str_resolution = machar._str_resolution.strip()
+ self._str_smallest_normal = machar._str_smallest_normal.strip()
+ self._str_smallest_subnormal = machar._str_smallest_subnormal.strip()
+ return self
+
+ def __str__(self):
+ fmt = (
+ 'Machine parameters for %(dtype)s\n'
+ '---------------------------------------------------------------\n'
+ 'precision = %(precision)3s resolution = %(_str_resolution)s\n'
+ 'machep = %(machep)6s eps = %(_str_eps)s\n'
+ 'negep = %(negep)6s epsneg = %(_str_epsneg)s\n'
+ 'minexp = %(minexp)6s tiny = %(_str_tiny)s\n'
+ 'maxexp = %(maxexp)6s max = %(_str_max)s\n'
+ 'nexp = %(nexp)6s min = -max\n'
+ 'smallest_normal = %(_str_smallest_normal)s '
+ 'smallest_subnormal = %(_str_smallest_subnormal)s\n'
+ '---------------------------------------------------------------\n'
+ )
+ return fmt % self.__dict__
+
+ def __repr__(self):
+ c = self.__class__.__name__
+ d = self.__dict__.copy()
+ d['klass'] = c
+ return (("%(klass)s(resolution=%(resolution)s, min=-%(_str_max)s,"
+ " max=%(_str_max)s, dtype=%(dtype)s)") % d)
+
+ @property
+ def smallest_normal(self):
+ """Return the value for the smallest normal.
+
+ Returns
+ -------
+ smallest_normal : float
+ Value for the smallest normal.
+
+ Warns
+ -----
+ UserWarning
+ If the calculated value for the smallest normal is requested for
+ double-double.
+ """
+ # This check is necessary because the value for smallest_normal is
+ # platform dependent for longdouble types.
+ if isnan(self._machar.smallest_normal.flat[0]):
+ warnings.warn(
+ 'The value of smallest normal is undefined for double double',
+ UserWarning, stacklevel=2)
+ return self._machar.smallest_normal.flat[0]
+
+ @property
+ def tiny(self):
+ """Return the value for tiny, alias of smallest_normal.
+
+ Returns
+ -------
+ tiny : float
+ Value for the smallest normal, alias of smallest_normal.
+
+ Warns
+ -----
+ UserWarning
+ If the calculated value for the smallest normal is requested for
+ double-double.
+ """
+ return self.smallest_normal
+
+
+@set_module('numpy')
+class iinfo:
+ """
+ iinfo(type)
+
+ Machine limits for integer types.
+
+ Attributes
+ ----------
+ bits : int
+ The number of bits occupied by the type.
+ dtype : dtype
+ Returns the dtype for which `iinfo` returns information.
+ min : int
+ The smallest integer expressible by the type.
+ max : int
+ The largest integer expressible by the type.
+
+ Parameters
+ ----------
+ int_type : integer type, dtype, or instance
+ The kind of integer data type to get information about.
+
+ See Also
+ --------
+ finfo : The equivalent for floating point data types.
+
+ Examples
+ --------
+ With types:
+
+ >>> import numpy as np
+ >>> ii16 = np.iinfo(np.int16)
+ >>> ii16.min
+ -32768
+ >>> ii16.max
+ 32767
+ >>> ii32 = np.iinfo(np.int32)
+ >>> ii32.min
+ -2147483648
+ >>> ii32.max
+ 2147483647
+
+ With instances:
+
+ >>> ii32 = np.iinfo(np.int32(10))
+ >>> ii32.min
+ -2147483648
+ >>> ii32.max
+ 2147483647
+
+ """
+
+ _min_vals = {}
+ _max_vals = {}
+
+ __class_getitem__ = classmethod(types.GenericAlias)
+
+ def __init__(self, int_type):
+ try:
+ self.dtype = numeric.dtype(int_type)
+ except TypeError:
+ self.dtype = numeric.dtype(type(int_type))
+ self.kind = self.dtype.kind
+ self.bits = self.dtype.itemsize * 8
+ self.key = "%s%d" % (self.kind, self.bits)
+ if self.kind not in 'iu':
+ raise ValueError("Invalid integer data type %r." % (self.kind,))
+
+ @property
+ def min(self):
+ """Minimum value of given dtype."""
+ if self.kind == 'u':
+ return 0
+ else:
+ try:
+ val = iinfo._min_vals[self.key]
+ except KeyError:
+ val = int(-(1 << (self.bits-1)))
+ iinfo._min_vals[self.key] = val
+ return val
+
+ @property
+ def max(self):
+ """Maximum value of given dtype."""
+ try:
+ val = iinfo._max_vals[self.key]
+ except KeyError:
+ if self.kind == 'u':
+ val = int((1 << self.bits) - 1)
+ else:
+ val = int((1 << (self.bits-1)) - 1)
+ iinfo._max_vals[self.key] = val
+ return val
+
+ def __str__(self):
+ """String representation."""
+ fmt = (
+ 'Machine parameters for %(dtype)s\n'
+ '---------------------------------------------------------------\n'
+ 'min = %(min)s\n'
+ 'max = %(max)s\n'
+ '---------------------------------------------------------------\n'
+ )
+ return fmt % {'dtype': self.dtype, 'min': self.min, 'max': self.max}
+
+ def __repr__(self):
+ return "%s(min=%s, max=%s, dtype=%s)" % (self.__class__.__name__,
+ self.min, self.max, self.dtype)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/getlimits.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/getlimits.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..9d79b178f4dc07ec25c365e06a186cc9ae2e5baf
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/getlimits.pyi
@@ -0,0 +1,3 @@
+from numpy import finfo, iinfo
+
+__all__ = ["finfo", "iinfo"]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/__multiarray_api.c b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/__multiarray_api.c
new file mode 100644
index 0000000000000000000000000000000000000000..c1a152704fa18c79f928b8fa6644f362579383f1
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/__multiarray_api.c
@@ -0,0 +1,376 @@
+
+/* These pointers will be stored in the C-object for use in other
+ extension modules
+*/
+
+void *PyArray_API[] = {
+ (void *) PyArray_GetNDArrayCVersion,
+ NULL,
+ (void *) &PyArray_Type,
+ (void *) &PyArrayDescr_Type,
+ NULL,
+ (void *) &PyArrayIter_Type,
+ (void *) &PyArrayMultiIter_Type,
+ (int *) &NPY_NUMUSERTYPES,
+ (void *) &PyBoolArrType_Type,
+ (void *) &_PyArrayScalar_BoolValues,
+ (void *) &PyGenericArrType_Type,
+ (void *) &PyNumberArrType_Type,
+ (void *) &PyIntegerArrType_Type,
+ (void *) &PySignedIntegerArrType_Type,
+ (void *) &PyUnsignedIntegerArrType_Type,
+ (void *) &PyInexactArrType_Type,
+ (void *) &PyFloatingArrType_Type,
+ (void *) &PyComplexFloatingArrType_Type,
+ (void *) &PyFlexibleArrType_Type,
+ (void *) &PyCharacterArrType_Type,
+ (void *) &PyByteArrType_Type,
+ (void *) &PyShortArrType_Type,
+ (void *) &PyIntArrType_Type,
+ (void *) &PyLongArrType_Type,
+ (void *) &PyLongLongArrType_Type,
+ (void *) &PyUByteArrType_Type,
+ (void *) &PyUShortArrType_Type,
+ (void *) &PyUIntArrType_Type,
+ (void *) &PyULongArrType_Type,
+ (void *) &PyULongLongArrType_Type,
+ (void *) &PyFloatArrType_Type,
+ (void *) &PyDoubleArrType_Type,
+ (void *) &PyLongDoubleArrType_Type,
+ (void *) &PyCFloatArrType_Type,
+ (void *) &PyCDoubleArrType_Type,
+ (void *) &PyCLongDoubleArrType_Type,
+ (void *) &PyObjectArrType_Type,
+ (void *) &PyStringArrType_Type,
+ (void *) &PyUnicodeArrType_Type,
+ (void *) &PyVoidArrType_Type,
+ NULL,
+ NULL,
+ (void *) PyArray_INCREF,
+ (void *) PyArray_XDECREF,
+ (void *) PyArray_SetStringFunction,
+ (void *) PyArray_DescrFromType,
+ (void *) PyArray_TypeObjectFromType,
+ (void *) PyArray_Zero,
+ (void *) PyArray_One,
+ (void *) PyArray_CastToType,
+ (void *) PyArray_CopyInto,
+ (void *) PyArray_CopyAnyInto,
+ (void *) PyArray_CanCastSafely,
+ (void *) PyArray_CanCastTo,
+ (void *) PyArray_ObjectType,
+ (void *) PyArray_DescrFromObject,
+ (void *) PyArray_ConvertToCommonType,
+ (void *) PyArray_DescrFromScalar,
+ (void *) PyArray_DescrFromTypeObject,
+ (void *) PyArray_Size,
+ (void *) PyArray_Scalar,
+ (void *) PyArray_FromScalar,
+ (void *) PyArray_ScalarAsCtype,
+ (void *) PyArray_CastScalarToCtype,
+ (void *) PyArray_CastScalarDirect,
+ (void *) PyArray_Pack,
+ NULL,
+ NULL,
+ NULL,
+ (void *) PyArray_FromAny,
+ (void *) PyArray_EnsureArray,
+ (void *) PyArray_EnsureAnyArray,
+ (void *) PyArray_FromFile,
+ (void *) PyArray_FromString,
+ (void *) PyArray_FromBuffer,
+ (void *) PyArray_FromIter,
+ (void *) PyArray_Return,
+ (void *) PyArray_GetField,
+ (void *) PyArray_SetField,
+ (void *) PyArray_Byteswap,
+ (void *) PyArray_Resize,
+ NULL,
+ NULL,
+ NULL,
+ (void *) PyArray_CopyObject,
+ (void *) PyArray_NewCopy,
+ (void *) PyArray_ToList,
+ (void *) PyArray_ToString,
+ (void *) PyArray_ToFile,
+ (void *) PyArray_Dump,
+ (void *) PyArray_Dumps,
+ (void *) PyArray_ValidType,
+ (void *) PyArray_UpdateFlags,
+ (void *) PyArray_New,
+ (void *) PyArray_NewFromDescr,
+ (void *) PyArray_DescrNew,
+ (void *) PyArray_DescrNewFromType,
+ (void *) PyArray_GetPriority,
+ (void *) PyArray_IterNew,
+ (void *) PyArray_MultiIterNew,
+ (void *) PyArray_PyIntAsInt,
+ (void *) PyArray_PyIntAsIntp,
+ (void *) PyArray_Broadcast,
+ NULL,
+ (void *) PyArray_FillWithScalar,
+ (void *) PyArray_CheckStrides,
+ (void *) PyArray_DescrNewByteorder,
+ (void *) PyArray_IterAllButAxis,
+ (void *) PyArray_CheckFromAny,
+ (void *) PyArray_FromArray,
+ (void *) PyArray_FromInterface,
+ (void *) PyArray_FromStructInterface,
+ (void *) PyArray_FromArrayAttr,
+ (void *) PyArray_ScalarKind,
+ (void *) PyArray_CanCoerceScalar,
+ NULL,
+ (void *) PyArray_CanCastScalar,
+ NULL,
+ (void *) PyArray_RemoveSmallest,
+ (void *) PyArray_ElementStrides,
+ (void *) PyArray_Item_INCREF,
+ (void *) PyArray_Item_XDECREF,
+ NULL,
+ (void *) PyArray_Transpose,
+ (void *) PyArray_TakeFrom,
+ (void *) PyArray_PutTo,
+ (void *) PyArray_PutMask,
+ (void *) PyArray_Repeat,
+ (void *) PyArray_Choose,
+ (void *) PyArray_Sort,
+ (void *) PyArray_ArgSort,
+ (void *) PyArray_SearchSorted,
+ (void *) PyArray_ArgMax,
+ (void *) PyArray_ArgMin,
+ (void *) PyArray_Reshape,
+ (void *) PyArray_Newshape,
+ (void *) PyArray_Squeeze,
+ (void *) PyArray_View,
+ (void *) PyArray_SwapAxes,
+ (void *) PyArray_Max,
+ (void *) PyArray_Min,
+ (void *) PyArray_Ptp,
+ (void *) PyArray_Mean,
+ (void *) PyArray_Trace,
+ (void *) PyArray_Diagonal,
+ (void *) PyArray_Clip,
+ (void *) PyArray_Conjugate,
+ (void *) PyArray_Nonzero,
+ (void *) PyArray_Std,
+ (void *) PyArray_Sum,
+ (void *) PyArray_CumSum,
+ (void *) PyArray_Prod,
+ (void *) PyArray_CumProd,
+ (void *) PyArray_All,
+ (void *) PyArray_Any,
+ (void *) PyArray_Compress,
+ (void *) PyArray_Flatten,
+ (void *) PyArray_Ravel,
+ (void *) PyArray_MultiplyList,
+ (void *) PyArray_MultiplyIntList,
+ (void *) PyArray_GetPtr,
+ (void *) PyArray_CompareLists,
+ (void *) PyArray_AsCArray,
+ NULL,
+ NULL,
+ (void *) PyArray_Free,
+ (void *) PyArray_Converter,
+ (void *) PyArray_IntpFromSequence,
+ (void *) PyArray_Concatenate,
+ (void *) PyArray_InnerProduct,
+ (void *) PyArray_MatrixProduct,
+ NULL,
+ (void *) PyArray_Correlate,
+ NULL,
+ (void *) PyArray_DescrConverter,
+ (void *) PyArray_DescrConverter2,
+ (void *) PyArray_IntpConverter,
+ (void *) PyArray_BufferConverter,
+ (void *) PyArray_AxisConverter,
+ (void *) PyArray_BoolConverter,
+ (void *) PyArray_ByteorderConverter,
+ (void *) PyArray_OrderConverter,
+ (void *) PyArray_EquivTypes,
+ (void *) PyArray_Zeros,
+ (void *) PyArray_Empty,
+ (void *) PyArray_Where,
+ (void *) PyArray_Arange,
+ (void *) PyArray_ArangeObj,
+ (void *) PyArray_SortkindConverter,
+ (void *) PyArray_LexSort,
+ (void *) PyArray_Round,
+ (void *) PyArray_EquivTypenums,
+ (void *) PyArray_RegisterDataType,
+ (void *) PyArray_RegisterCastFunc,
+ (void *) PyArray_RegisterCanCast,
+ (void *) PyArray_InitArrFuncs,
+ (void *) PyArray_IntTupleFromIntp,
+ NULL,
+ (void *) PyArray_ClipmodeConverter,
+ (void *) PyArray_OutputConverter,
+ (void *) PyArray_BroadcastToShape,
+ NULL,
+ NULL,
+ (void *) PyArray_DescrAlignConverter,
+ (void *) PyArray_DescrAlignConverter2,
+ (void *) PyArray_SearchsideConverter,
+ (void *) PyArray_CheckAxis,
+ (void *) PyArray_OverflowMultiplyList,
+ NULL,
+ (void *) PyArray_MultiIterFromObjects,
+ (void *) PyArray_GetEndianness,
+ (void *) PyArray_GetNDArrayCFeatureVersion,
+ (void *) PyArray_Correlate2,
+ (void *) PyArray_NeighborhoodIterNew,
+ (void *) &PyTimeIntegerArrType_Type,
+ (void *) &PyDatetimeArrType_Type,
+ (void *) &PyTimedeltaArrType_Type,
+ (void *) &PyHalfArrType_Type,
+ (void *) &NpyIter_Type,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ (void *) NpyIter_New,
+ (void *) NpyIter_MultiNew,
+ (void *) NpyIter_AdvancedNew,
+ (void *) NpyIter_Copy,
+ (void *) NpyIter_Deallocate,
+ (void *) NpyIter_HasDelayedBufAlloc,
+ (void *) NpyIter_HasExternalLoop,
+ (void *) NpyIter_EnableExternalLoop,
+ (void *) NpyIter_GetInnerStrideArray,
+ (void *) NpyIter_GetInnerLoopSizePtr,
+ (void *) NpyIter_Reset,
+ (void *) NpyIter_ResetBasePointers,
+ (void *) NpyIter_ResetToIterIndexRange,
+ (void *) NpyIter_GetNDim,
+ (void *) NpyIter_GetNOp,
+ (void *) NpyIter_GetIterNext,
+ (void *) NpyIter_GetIterSize,
+ (void *) NpyIter_GetIterIndexRange,
+ (void *) NpyIter_GetIterIndex,
+ (void *) NpyIter_GotoIterIndex,
+ (void *) NpyIter_HasMultiIndex,
+ (void *) NpyIter_GetShape,
+ (void *) NpyIter_GetGetMultiIndex,
+ (void *) NpyIter_GotoMultiIndex,
+ (void *) NpyIter_RemoveMultiIndex,
+ (void *) NpyIter_HasIndex,
+ (void *) NpyIter_IsBuffered,
+ (void *) NpyIter_IsGrowInner,
+ (void *) NpyIter_GetBufferSize,
+ (void *) NpyIter_GetIndexPtr,
+ (void *) NpyIter_GotoIndex,
+ (void *) NpyIter_GetDataPtrArray,
+ (void *) NpyIter_GetDescrArray,
+ (void *) NpyIter_GetOperandArray,
+ (void *) NpyIter_GetIterView,
+ (void *) NpyIter_GetReadFlags,
+ (void *) NpyIter_GetWriteFlags,
+ (void *) NpyIter_DebugPrint,
+ (void *) NpyIter_IterationNeedsAPI,
+ (void *) NpyIter_GetInnerFixedStrideArray,
+ (void *) NpyIter_RemoveAxis,
+ (void *) NpyIter_GetAxisStrideArray,
+ (void *) NpyIter_RequiresBuffering,
+ (void *) NpyIter_GetInitialDataPtrArray,
+ (void *) NpyIter_CreateCompatibleStrides,
+ (void *) PyArray_CastingConverter,
+ (void *) PyArray_CountNonzero,
+ (void *) PyArray_PromoteTypes,
+ (void *) PyArray_MinScalarType,
+ (void *) PyArray_ResultType,
+ (void *) PyArray_CanCastArrayTo,
+ (void *) PyArray_CanCastTypeTo,
+ (void *) PyArray_EinsteinSum,
+ (void *) PyArray_NewLikeArray,
+ NULL,
+ (void *) PyArray_ConvertClipmodeSequence,
+ (void *) PyArray_MatrixProduct2,
+ (void *) NpyIter_IsFirstVisit,
+ (void *) PyArray_SetBaseObject,
+ (void *) PyArray_CreateSortedStridePerm,
+ (void *) PyArray_RemoveAxesInPlace,
+ (void *) PyArray_DebugPrint,
+ (void *) PyArray_FailUnlessWriteable,
+ (void *) PyArray_SetUpdateIfCopyBase,
+ (void *) PyDataMem_NEW,
+ (void *) PyDataMem_FREE,
+ (void *) PyDataMem_RENEW,
+ NULL,
+ (NPY_CASTING *) &NPY_DEFAULT_ASSIGN_CASTING,
+ NULL,
+ NULL,
+ NULL,
+ (void *) PyArray_Partition,
+ (void *) PyArray_ArgPartition,
+ (void *) PyArray_SelectkindConverter,
+ (void *) PyDataMem_NEW_ZEROED,
+ (void *) PyArray_CheckAnyScalarExact,
+ NULL,
+ (void *) PyArray_ResolveWritebackIfCopy,
+ (void *) PyArray_SetWritebackIfCopyBase,
+ (void *) PyDataMem_SetHandler,
+ (void *) PyDataMem_GetHandler,
+ (PyObject* *) &PyDataMem_DefaultHandler,
+ (void *) NpyDatetime_ConvertDatetime64ToDatetimeStruct,
+ (void *) NpyDatetime_ConvertDatetimeStructToDatetime64,
+ (void *) NpyDatetime_ConvertPyDateTimeToDatetimeStruct,
+ (void *) NpyDatetime_GetDatetimeISO8601StrLen,
+ (void *) NpyDatetime_MakeISO8601Datetime,
+ (void *) NpyDatetime_ParseISO8601Datetime,
+ (void *) NpyString_load,
+ (void *) NpyString_pack,
+ (void *) NpyString_pack_null,
+ (void *) NpyString_acquire_allocator,
+ (void *) NpyString_acquire_allocators,
+ (void *) NpyString_release_allocator,
+ (void *) NpyString_release_allocators,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ (void *) PyArray_GetDefaultDescr,
+ (void *) PyArrayInitDTypeMeta_FromSpec,
+ (void *) PyArray_CommonDType,
+ (void *) PyArray_PromoteDTypeSequence,
+ (void *) _PyDataType_GetArrFuncs,
+ NULL,
+ NULL,
+ NULL
+};
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/__multiarray_api.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/__multiarray_api.h
new file mode 100644
index 0000000000000000000000000000000000000000..cfc3628aa53e41f22d81877df31d40020519bebf
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/__multiarray_api.h
@@ -0,0 +1,1613 @@
+
+#if defined(_MULTIARRAYMODULE) || defined(WITH_CPYCHECKER_STEALS_REFERENCE_TO_ARG_ATTRIBUTE)
+
+typedef struct {
+ PyObject_HEAD
+ npy_bool obval;
+} PyBoolScalarObject;
+
+extern NPY_NO_EXPORT PyTypeObject PyArrayNeighborhoodIter_Type;
+extern NPY_NO_EXPORT PyBoolScalarObject _PyArrayScalar_BoolValues[2];
+
+NPY_NO_EXPORT unsigned int PyArray_GetNDArrayCVersion \
+ (void);
+extern NPY_NO_EXPORT PyTypeObject PyArray_Type;
+
+extern NPY_NO_EXPORT PyArray_DTypeMeta PyArrayDescr_TypeFull;
+#define PyArrayDescr_Type (*(PyTypeObject *)(&PyArrayDescr_TypeFull))
+
+extern NPY_NO_EXPORT PyTypeObject PyArrayIter_Type;
+
+extern NPY_NO_EXPORT PyTypeObject PyArrayMultiIter_Type;
+
+extern NPY_NO_EXPORT int NPY_NUMUSERTYPES;
+
+extern NPY_NO_EXPORT PyTypeObject PyBoolArrType_Type;
+
+extern NPY_NO_EXPORT PyBoolScalarObject _PyArrayScalar_BoolValues[2];
+
+extern NPY_NO_EXPORT PyTypeObject PyGenericArrType_Type;
+
+extern NPY_NO_EXPORT PyTypeObject PyNumberArrType_Type;
+
+extern NPY_NO_EXPORT PyTypeObject PyIntegerArrType_Type;
+
+extern NPY_NO_EXPORT PyTypeObject PySignedIntegerArrType_Type;
+
+extern NPY_NO_EXPORT PyTypeObject PyUnsignedIntegerArrType_Type;
+
+extern NPY_NO_EXPORT PyTypeObject PyInexactArrType_Type;
+
+extern NPY_NO_EXPORT PyTypeObject PyFloatingArrType_Type;
+
+extern NPY_NO_EXPORT PyTypeObject PyComplexFloatingArrType_Type;
+
+extern NPY_NO_EXPORT PyTypeObject PyFlexibleArrType_Type;
+
+extern NPY_NO_EXPORT PyTypeObject PyCharacterArrType_Type;
+
+extern NPY_NO_EXPORT PyTypeObject PyByteArrType_Type;
+
+extern NPY_NO_EXPORT PyTypeObject PyShortArrType_Type;
+
+extern NPY_NO_EXPORT PyTypeObject PyIntArrType_Type;
+
+extern NPY_NO_EXPORT PyTypeObject PyLongArrType_Type;
+
+extern NPY_NO_EXPORT PyTypeObject PyLongLongArrType_Type;
+
+extern NPY_NO_EXPORT PyTypeObject PyUByteArrType_Type;
+
+extern NPY_NO_EXPORT PyTypeObject PyUShortArrType_Type;
+
+extern NPY_NO_EXPORT PyTypeObject PyUIntArrType_Type;
+
+extern NPY_NO_EXPORT PyTypeObject PyULongArrType_Type;
+
+extern NPY_NO_EXPORT PyTypeObject PyULongLongArrType_Type;
+
+extern NPY_NO_EXPORT PyTypeObject PyFloatArrType_Type;
+
+extern NPY_NO_EXPORT PyTypeObject PyDoubleArrType_Type;
+
+extern NPY_NO_EXPORT PyTypeObject PyLongDoubleArrType_Type;
+
+extern NPY_NO_EXPORT PyTypeObject PyCFloatArrType_Type;
+
+extern NPY_NO_EXPORT PyTypeObject PyCDoubleArrType_Type;
+
+extern NPY_NO_EXPORT PyTypeObject PyCLongDoubleArrType_Type;
+
+extern NPY_NO_EXPORT PyTypeObject PyObjectArrType_Type;
+
+extern NPY_NO_EXPORT PyTypeObject PyStringArrType_Type;
+
+extern NPY_NO_EXPORT PyTypeObject PyUnicodeArrType_Type;
+
+extern NPY_NO_EXPORT PyTypeObject PyVoidArrType_Type;
+
+NPY_NO_EXPORT int PyArray_INCREF \
+ (PyArrayObject *);
+NPY_NO_EXPORT int PyArray_XDECREF \
+ (PyArrayObject *);
+NPY_NO_EXPORT void PyArray_SetStringFunction \
+ (PyObject *, int);
+NPY_NO_EXPORT PyArray_Descr * PyArray_DescrFromType \
+ (int);
+NPY_NO_EXPORT PyObject * PyArray_TypeObjectFromType \
+ (int);
+NPY_NO_EXPORT char * PyArray_Zero \
+ (PyArrayObject *);
+NPY_NO_EXPORT char * PyArray_One \
+ (PyArrayObject *);
+NPY_NO_EXPORT NPY_STEALS_REF_TO_ARG(2) PyObject * PyArray_CastToType \
+ (PyArrayObject *, PyArray_Descr *, int);
+NPY_NO_EXPORT int PyArray_CopyInto \
+ (PyArrayObject *, PyArrayObject *);
+NPY_NO_EXPORT int PyArray_CopyAnyInto \
+ (PyArrayObject *, PyArrayObject *);
+NPY_NO_EXPORT int PyArray_CanCastSafely \
+ (int, int);
+NPY_NO_EXPORT npy_bool PyArray_CanCastTo \
+ (PyArray_Descr *, PyArray_Descr *);
+NPY_NO_EXPORT int PyArray_ObjectType \
+ (PyObject *, int);
+NPY_NO_EXPORT PyArray_Descr * PyArray_DescrFromObject \
+ (PyObject *, PyArray_Descr *);
+NPY_NO_EXPORT PyArrayObject ** PyArray_ConvertToCommonType \
+ (PyObject *, int *);
+NPY_NO_EXPORT PyArray_Descr * PyArray_DescrFromScalar \
+ (PyObject *);
+NPY_NO_EXPORT PyArray_Descr * PyArray_DescrFromTypeObject \
+ (PyObject *);
+NPY_NO_EXPORT npy_intp PyArray_Size \
+ (PyObject *);
+NPY_NO_EXPORT PyObject * PyArray_Scalar \
+ (void *, PyArray_Descr *, PyObject *);
+NPY_NO_EXPORT NPY_STEALS_REF_TO_ARG(2) PyObject * PyArray_FromScalar \
+ (PyObject *, PyArray_Descr *);
+NPY_NO_EXPORT void PyArray_ScalarAsCtype \
+ (PyObject *, void *);
+NPY_NO_EXPORT int PyArray_CastScalarToCtype \
+ (PyObject *, void *, PyArray_Descr *);
+NPY_NO_EXPORT int PyArray_CastScalarDirect \
+ (PyObject *, PyArray_Descr *, void *, int);
+NPY_NO_EXPORT int PyArray_Pack \
+ (PyArray_Descr *, void *, PyObject *);
+NPY_NO_EXPORT NPY_STEALS_REF_TO_ARG(2) PyObject * PyArray_FromAny \
+ (PyObject *, PyArray_Descr *, int, int, int, PyObject *);
+NPY_NO_EXPORT NPY_STEALS_REF_TO_ARG(1) PyObject * PyArray_EnsureArray \
+ (PyObject *);
+NPY_NO_EXPORT NPY_STEALS_REF_TO_ARG(1) PyObject * PyArray_EnsureAnyArray \
+ (PyObject *);
+NPY_NO_EXPORT PyObject * PyArray_FromFile \
+ (FILE *, PyArray_Descr *, npy_intp, char *);
+NPY_NO_EXPORT PyObject * PyArray_FromString \
+ (char *, npy_intp, PyArray_Descr *, npy_intp, char *);
+NPY_NO_EXPORT PyObject * PyArray_FromBuffer \
+ (PyObject *, PyArray_Descr *, npy_intp, npy_intp);
+NPY_NO_EXPORT NPY_STEALS_REF_TO_ARG(2) PyObject * PyArray_FromIter \
+ (PyObject *, PyArray_Descr *, npy_intp);
+NPY_NO_EXPORT NPY_STEALS_REF_TO_ARG(1) PyObject * PyArray_Return \
+ (PyArrayObject *);
+NPY_NO_EXPORT NPY_STEALS_REF_TO_ARG(2) PyObject * PyArray_GetField \
+ (PyArrayObject *, PyArray_Descr *, int);
+NPY_NO_EXPORT NPY_STEALS_REF_TO_ARG(2) int PyArray_SetField \
+ (PyArrayObject *, PyArray_Descr *, int, PyObject *);
+NPY_NO_EXPORT PyObject * PyArray_Byteswap \
+ (PyArrayObject *, npy_bool);
+NPY_NO_EXPORT PyObject * PyArray_Resize \
+ (PyArrayObject *, PyArray_Dims *, int, NPY_ORDER NPY_UNUSED(order));
+NPY_NO_EXPORT int PyArray_CopyObject \
+ (PyArrayObject *, PyObject *);
+NPY_NO_EXPORT PyObject * PyArray_NewCopy \
+ (PyArrayObject *, NPY_ORDER);
+NPY_NO_EXPORT PyObject * PyArray_ToList \
+ (PyArrayObject *);
+NPY_NO_EXPORT PyObject * PyArray_ToString \
+ (PyArrayObject *, NPY_ORDER);
+NPY_NO_EXPORT int PyArray_ToFile \
+ (PyArrayObject *, FILE *, char *, char *);
+NPY_NO_EXPORT int PyArray_Dump \
+ (PyObject *, PyObject *, int);
+NPY_NO_EXPORT PyObject * PyArray_Dumps \
+ (PyObject *, int);
+NPY_NO_EXPORT int PyArray_ValidType \
+ (int);
+NPY_NO_EXPORT void PyArray_UpdateFlags \
+ (PyArrayObject *, int);
+NPY_NO_EXPORT PyObject * PyArray_New \
+ (PyTypeObject *, int, npy_intp const *, int, npy_intp const *, void *, int, int, PyObject *);
+NPY_NO_EXPORT NPY_STEALS_REF_TO_ARG(2) PyObject * PyArray_NewFromDescr \
+ (PyTypeObject *, PyArray_Descr *, int, npy_intp const *, npy_intp const *, void *, int, PyObject *);
+NPY_NO_EXPORT PyArray_Descr * PyArray_DescrNew \
+ (PyArray_Descr *);
+NPY_NO_EXPORT PyArray_Descr * PyArray_DescrNewFromType \
+ (int);
+NPY_NO_EXPORT double PyArray_GetPriority \
+ (PyObject *, double);
+NPY_NO_EXPORT PyObject * PyArray_IterNew \
+ (PyObject *);
+NPY_NO_EXPORT PyObject* PyArray_MultiIterNew \
+ (int, ...);
+NPY_NO_EXPORT int PyArray_PyIntAsInt \
+ (PyObject *);
+NPY_NO_EXPORT npy_intp PyArray_PyIntAsIntp \
+ (PyObject *);
+NPY_NO_EXPORT int PyArray_Broadcast \
+ (PyArrayMultiIterObject *);
+NPY_NO_EXPORT int PyArray_FillWithScalar \
+ (PyArrayObject *, PyObject *);
+NPY_NO_EXPORT npy_bool PyArray_CheckStrides \
+ (int, int, npy_intp, npy_intp, npy_intp const *, npy_intp const *);
+NPY_NO_EXPORT PyArray_Descr * PyArray_DescrNewByteorder \
+ (PyArray_Descr *, char);
+NPY_NO_EXPORT PyObject * PyArray_IterAllButAxis \
+ (PyObject *, int *);
+NPY_NO_EXPORT NPY_STEALS_REF_TO_ARG(2) PyObject * PyArray_CheckFromAny \
+ (PyObject *, PyArray_Descr *, int, int, int, PyObject *);
+NPY_NO_EXPORT NPY_STEALS_REF_TO_ARG(2) PyObject * PyArray_FromArray \
+ (PyArrayObject *, PyArray_Descr *, int);
+NPY_NO_EXPORT PyObject * PyArray_FromInterface \
+ (PyObject *);
+NPY_NO_EXPORT PyObject * PyArray_FromStructInterface \
+ (PyObject *);
+NPY_NO_EXPORT PyObject * PyArray_FromArrayAttr \
+ (PyObject *, PyArray_Descr *, PyObject *);
+NPY_NO_EXPORT NPY_SCALARKIND PyArray_ScalarKind \
+ (int, PyArrayObject **);
+NPY_NO_EXPORT int PyArray_CanCoerceScalar \
+ (int, int, NPY_SCALARKIND);
+NPY_NO_EXPORT npy_bool PyArray_CanCastScalar \
+ (PyTypeObject *, PyTypeObject *);
+NPY_NO_EXPORT int PyArray_RemoveSmallest \
+ (PyArrayMultiIterObject *);
+NPY_NO_EXPORT int PyArray_ElementStrides \
+ (PyObject *);
+NPY_NO_EXPORT void PyArray_Item_INCREF \
+ (char *, PyArray_Descr *);
+NPY_NO_EXPORT void PyArray_Item_XDECREF \
+ (char *, PyArray_Descr *);
+NPY_NO_EXPORT PyObject * PyArray_Transpose \
+ (PyArrayObject *, PyArray_Dims *);
+NPY_NO_EXPORT PyObject * PyArray_TakeFrom \
+ (PyArrayObject *, PyObject *, int, PyArrayObject *, NPY_CLIPMODE);
+NPY_NO_EXPORT PyObject * PyArray_PutTo \
+ (PyArrayObject *, PyObject*, PyObject *, NPY_CLIPMODE);
+NPY_NO_EXPORT PyObject * PyArray_PutMask \
+ (PyArrayObject *, PyObject*, PyObject*);
+NPY_NO_EXPORT PyObject * PyArray_Repeat \
+ (PyArrayObject *, PyObject *, int);
+NPY_NO_EXPORT PyObject * PyArray_Choose \
+ (PyArrayObject *, PyObject *, PyArrayObject *, NPY_CLIPMODE);
+NPY_NO_EXPORT int PyArray_Sort \
+ (PyArrayObject *, int, NPY_SORTKIND);
+NPY_NO_EXPORT PyObject * PyArray_ArgSort \
+ (PyArrayObject *, int, NPY_SORTKIND);
+NPY_NO_EXPORT PyObject * PyArray_SearchSorted \
+ (PyArrayObject *, PyObject *, NPY_SEARCHSIDE, PyObject *);
+NPY_NO_EXPORT PyObject * PyArray_ArgMax \
+ (PyArrayObject *, int, PyArrayObject *);
+NPY_NO_EXPORT PyObject * PyArray_ArgMin \
+ (PyArrayObject *, int, PyArrayObject *);
+NPY_NO_EXPORT PyObject * PyArray_Reshape \
+ (PyArrayObject *, PyObject *);
+NPY_NO_EXPORT PyObject * PyArray_Newshape \
+ (PyArrayObject *, PyArray_Dims *, NPY_ORDER);
+NPY_NO_EXPORT PyObject * PyArray_Squeeze \
+ (PyArrayObject *);
+NPY_NO_EXPORT NPY_STEALS_REF_TO_ARG(2) PyObject * PyArray_View \
+ (PyArrayObject *, PyArray_Descr *, PyTypeObject *);
+NPY_NO_EXPORT PyObject * PyArray_SwapAxes \
+ (PyArrayObject *, int, int);
+NPY_NO_EXPORT PyObject * PyArray_Max \
+ (PyArrayObject *, int, PyArrayObject *);
+NPY_NO_EXPORT PyObject * PyArray_Min \
+ (PyArrayObject *, int, PyArrayObject *);
+NPY_NO_EXPORT PyObject * PyArray_Ptp \
+ (PyArrayObject *, int, PyArrayObject *);
+NPY_NO_EXPORT PyObject * PyArray_Mean \
+ (PyArrayObject *, int, int, PyArrayObject *);
+NPY_NO_EXPORT PyObject * PyArray_Trace \
+ (PyArrayObject *, int, int, int, int, PyArrayObject *);
+NPY_NO_EXPORT PyObject * PyArray_Diagonal \
+ (PyArrayObject *, int, int, int);
+NPY_NO_EXPORT PyObject * PyArray_Clip \
+ (PyArrayObject *, PyObject *, PyObject *, PyArrayObject *);
+NPY_NO_EXPORT PyObject * PyArray_Conjugate \
+ (PyArrayObject *, PyArrayObject *);
+NPY_NO_EXPORT PyObject * PyArray_Nonzero \
+ (PyArrayObject *);
+NPY_NO_EXPORT PyObject * PyArray_Std \
+ (PyArrayObject *, int, int, PyArrayObject *, int);
+NPY_NO_EXPORT PyObject * PyArray_Sum \
+ (PyArrayObject *, int, int, PyArrayObject *);
+NPY_NO_EXPORT PyObject * PyArray_CumSum \
+ (PyArrayObject *, int, int, PyArrayObject *);
+NPY_NO_EXPORT PyObject * PyArray_Prod \
+ (PyArrayObject *, int, int, PyArrayObject *);
+NPY_NO_EXPORT PyObject * PyArray_CumProd \
+ (PyArrayObject *, int, int, PyArrayObject *);
+NPY_NO_EXPORT PyObject * PyArray_All \
+ (PyArrayObject *, int, PyArrayObject *);
+NPY_NO_EXPORT PyObject * PyArray_Any \
+ (PyArrayObject *, int, PyArrayObject *);
+NPY_NO_EXPORT PyObject * PyArray_Compress \
+ (PyArrayObject *, PyObject *, int, PyArrayObject *);
+NPY_NO_EXPORT PyObject * PyArray_Flatten \
+ (PyArrayObject *, NPY_ORDER);
+NPY_NO_EXPORT PyObject * PyArray_Ravel \
+ (PyArrayObject *, NPY_ORDER);
+NPY_NO_EXPORT npy_intp PyArray_MultiplyList \
+ (npy_intp const *, int);
+NPY_NO_EXPORT int PyArray_MultiplyIntList \
+ (int const *, int);
+NPY_NO_EXPORT void * PyArray_GetPtr \
+ (PyArrayObject *, npy_intp const*);
+NPY_NO_EXPORT int PyArray_CompareLists \
+ (npy_intp const *, npy_intp const *, int);
+NPY_NO_EXPORT NPY_STEALS_REF_TO_ARG(5) int PyArray_AsCArray \
+ (PyObject **, void *, npy_intp *, int, PyArray_Descr*);
+NPY_NO_EXPORT int PyArray_Free \
+ (PyObject *, void *);
+NPY_NO_EXPORT int PyArray_Converter \
+ (PyObject *, PyObject **);
+NPY_NO_EXPORT int PyArray_IntpFromSequence \
+ (PyObject *, npy_intp *, int);
+NPY_NO_EXPORT PyObject * PyArray_Concatenate \
+ (PyObject *, int);
+NPY_NO_EXPORT PyObject * PyArray_InnerProduct \
+ (PyObject *, PyObject *);
+NPY_NO_EXPORT PyObject * PyArray_MatrixProduct \
+ (PyObject *, PyObject *);
+NPY_NO_EXPORT PyObject * PyArray_Correlate \
+ (PyObject *, PyObject *, int);
+NPY_NO_EXPORT int PyArray_DescrConverter \
+ (PyObject *, PyArray_Descr **);
+NPY_NO_EXPORT int PyArray_DescrConverter2 \
+ (PyObject *, PyArray_Descr **);
+NPY_NO_EXPORT int PyArray_IntpConverter \
+ (PyObject *, PyArray_Dims *);
+NPY_NO_EXPORT int PyArray_BufferConverter \
+ (PyObject *, PyArray_Chunk *);
+NPY_NO_EXPORT int PyArray_AxisConverter \
+ (PyObject *, int *);
+NPY_NO_EXPORT int PyArray_BoolConverter \
+ (PyObject *, npy_bool *);
+NPY_NO_EXPORT int PyArray_ByteorderConverter \
+ (PyObject *, char *);
+NPY_NO_EXPORT int PyArray_OrderConverter \
+ (PyObject *, NPY_ORDER *);
+NPY_NO_EXPORT unsigned char PyArray_EquivTypes \
+ (PyArray_Descr *, PyArray_Descr *);
+NPY_NO_EXPORT NPY_STEALS_REF_TO_ARG(3) PyObject * PyArray_Zeros \
+ (int, npy_intp const *, PyArray_Descr *, int);
+NPY_NO_EXPORT NPY_STEALS_REF_TO_ARG(3) PyObject * PyArray_Empty \
+ (int, npy_intp const *, PyArray_Descr *, int);
+NPY_NO_EXPORT PyObject * PyArray_Where \
+ (PyObject *, PyObject *, PyObject *);
+NPY_NO_EXPORT PyObject * PyArray_Arange \
+ (double, double, double, int);
+NPY_NO_EXPORT PyObject * PyArray_ArangeObj \
+ (PyObject *, PyObject *, PyObject *, PyArray_Descr *);
+NPY_NO_EXPORT int PyArray_SortkindConverter \
+ (PyObject *, NPY_SORTKIND *);
+NPY_NO_EXPORT PyObject * PyArray_LexSort \
+ (PyObject *, int);
+NPY_NO_EXPORT PyObject * PyArray_Round \
+ (PyArrayObject *, int, PyArrayObject *);
+NPY_NO_EXPORT unsigned char PyArray_EquivTypenums \
+ (int, int);
+NPY_NO_EXPORT int PyArray_RegisterDataType \
+ (PyArray_DescrProto *);
+NPY_NO_EXPORT int PyArray_RegisterCastFunc \
+ (PyArray_Descr *, int, PyArray_VectorUnaryFunc *);
+NPY_NO_EXPORT int PyArray_RegisterCanCast \
+ (PyArray_Descr *, int, NPY_SCALARKIND);
+NPY_NO_EXPORT void PyArray_InitArrFuncs \
+ (PyArray_ArrFuncs *);
+NPY_NO_EXPORT PyObject * PyArray_IntTupleFromIntp \
+ (int, npy_intp const *);
+NPY_NO_EXPORT int PyArray_ClipmodeConverter \
+ (PyObject *, NPY_CLIPMODE *);
+NPY_NO_EXPORT int PyArray_OutputConverter \
+ (PyObject *, PyArrayObject **);
+NPY_NO_EXPORT PyObject * PyArray_BroadcastToShape \
+ (PyObject *, npy_intp *, int);
+NPY_NO_EXPORT int PyArray_DescrAlignConverter \
+ (PyObject *, PyArray_Descr **);
+NPY_NO_EXPORT int PyArray_DescrAlignConverter2 \
+ (PyObject *, PyArray_Descr **);
+NPY_NO_EXPORT int PyArray_SearchsideConverter \
+ (PyObject *, void *);
+NPY_NO_EXPORT PyObject * PyArray_CheckAxis \
+ (PyArrayObject *, int *, int);
+NPY_NO_EXPORT npy_intp PyArray_OverflowMultiplyList \
+ (npy_intp const *, int);
+NPY_NO_EXPORT PyObject* PyArray_MultiIterFromObjects \
+ (PyObject **, int, int, ...);
+NPY_NO_EXPORT int PyArray_GetEndianness \
+ (void);
+NPY_NO_EXPORT unsigned int PyArray_GetNDArrayCFeatureVersion \
+ (void);
+NPY_NO_EXPORT PyObject * PyArray_Correlate2 \
+ (PyObject *, PyObject *, int);
+NPY_NO_EXPORT PyObject* PyArray_NeighborhoodIterNew \
+ (PyArrayIterObject *, const npy_intp *, int, PyArrayObject*);
+extern NPY_NO_EXPORT PyTypeObject PyTimeIntegerArrType_Type;
+
+extern NPY_NO_EXPORT PyTypeObject PyDatetimeArrType_Type;
+
+extern NPY_NO_EXPORT PyTypeObject PyTimedeltaArrType_Type;
+
+extern NPY_NO_EXPORT PyTypeObject PyHalfArrType_Type;
+
+extern NPY_NO_EXPORT PyTypeObject NpyIter_Type;
+
+NPY_NO_EXPORT NpyIter * NpyIter_New \
+ (PyArrayObject *, npy_uint32, NPY_ORDER, NPY_CASTING, PyArray_Descr*);
+NPY_NO_EXPORT NpyIter * NpyIter_MultiNew \
+ (int, PyArrayObject **, npy_uint32, NPY_ORDER, NPY_CASTING, npy_uint32 *, PyArray_Descr **);
+NPY_NO_EXPORT NpyIter * NpyIter_AdvancedNew \
+ (int, PyArrayObject **, npy_uint32, NPY_ORDER, NPY_CASTING, npy_uint32 *, PyArray_Descr **, int, int **, npy_intp *, npy_intp);
+NPY_NO_EXPORT NpyIter * NpyIter_Copy \
+ (NpyIter *);
+NPY_NO_EXPORT int NpyIter_Deallocate \
+ (NpyIter *);
+NPY_NO_EXPORT npy_bool NpyIter_HasDelayedBufAlloc \
+ (NpyIter *);
+NPY_NO_EXPORT npy_bool NpyIter_HasExternalLoop \
+ (NpyIter *);
+NPY_NO_EXPORT int NpyIter_EnableExternalLoop \
+ (NpyIter *);
+NPY_NO_EXPORT npy_intp * NpyIter_GetInnerStrideArray \
+ (NpyIter *);
+NPY_NO_EXPORT npy_intp * NpyIter_GetInnerLoopSizePtr \
+ (NpyIter *);
+NPY_NO_EXPORT int NpyIter_Reset \
+ (NpyIter *, char **);
+NPY_NO_EXPORT int NpyIter_ResetBasePointers \
+ (NpyIter *, char **, char **);
+NPY_NO_EXPORT int NpyIter_ResetToIterIndexRange \
+ (NpyIter *, npy_intp, npy_intp, char **);
+NPY_NO_EXPORT int NpyIter_GetNDim \
+ (NpyIter *);
+NPY_NO_EXPORT int NpyIter_GetNOp \
+ (NpyIter *);
+NPY_NO_EXPORT NpyIter_IterNextFunc * NpyIter_GetIterNext \
+ (NpyIter *, char **);
+NPY_NO_EXPORT npy_intp NpyIter_GetIterSize \
+ (NpyIter *);
+NPY_NO_EXPORT void NpyIter_GetIterIndexRange \
+ (NpyIter *, npy_intp *, npy_intp *);
+NPY_NO_EXPORT npy_intp NpyIter_GetIterIndex \
+ (NpyIter *);
+NPY_NO_EXPORT int NpyIter_GotoIterIndex \
+ (NpyIter *, npy_intp);
+NPY_NO_EXPORT npy_bool NpyIter_HasMultiIndex \
+ (NpyIter *);
+NPY_NO_EXPORT int NpyIter_GetShape \
+ (NpyIter *, npy_intp *);
+NPY_NO_EXPORT NpyIter_GetMultiIndexFunc * NpyIter_GetGetMultiIndex \
+ (NpyIter *, char **);
+NPY_NO_EXPORT int NpyIter_GotoMultiIndex \
+ (NpyIter *, npy_intp const *);
+NPY_NO_EXPORT int NpyIter_RemoveMultiIndex \
+ (NpyIter *);
+NPY_NO_EXPORT npy_bool NpyIter_HasIndex \
+ (NpyIter *);
+NPY_NO_EXPORT npy_bool NpyIter_IsBuffered \
+ (NpyIter *);
+NPY_NO_EXPORT npy_bool NpyIter_IsGrowInner \
+ (NpyIter *);
+NPY_NO_EXPORT npy_intp NpyIter_GetBufferSize \
+ (NpyIter *);
+NPY_NO_EXPORT npy_intp * NpyIter_GetIndexPtr \
+ (NpyIter *);
+NPY_NO_EXPORT int NpyIter_GotoIndex \
+ (NpyIter *, npy_intp);
+NPY_NO_EXPORT char ** NpyIter_GetDataPtrArray \
+ (NpyIter *);
+NPY_NO_EXPORT PyArray_Descr ** NpyIter_GetDescrArray \
+ (NpyIter *);
+NPY_NO_EXPORT PyArrayObject ** NpyIter_GetOperandArray \
+ (NpyIter *);
+NPY_NO_EXPORT PyArrayObject * NpyIter_GetIterView \
+ (NpyIter *, npy_intp);
+NPY_NO_EXPORT void NpyIter_GetReadFlags \
+ (NpyIter *, char *);
+NPY_NO_EXPORT void NpyIter_GetWriteFlags \
+ (NpyIter *, char *);
+NPY_NO_EXPORT void NpyIter_DebugPrint \
+ (NpyIter *);
+NPY_NO_EXPORT npy_bool NpyIter_IterationNeedsAPI \
+ (NpyIter *);
+NPY_NO_EXPORT void NpyIter_GetInnerFixedStrideArray \
+ (NpyIter *, npy_intp *);
+NPY_NO_EXPORT int NpyIter_RemoveAxis \
+ (NpyIter *, int);
+NPY_NO_EXPORT npy_intp * NpyIter_GetAxisStrideArray \
+ (NpyIter *, int);
+NPY_NO_EXPORT npy_bool NpyIter_RequiresBuffering \
+ (NpyIter *);
+NPY_NO_EXPORT char ** NpyIter_GetInitialDataPtrArray \
+ (NpyIter *);
+NPY_NO_EXPORT int NpyIter_CreateCompatibleStrides \
+ (NpyIter *, npy_intp, npy_intp *);
+NPY_NO_EXPORT int PyArray_CastingConverter \
+ (PyObject *, NPY_CASTING *);
+NPY_NO_EXPORT npy_intp PyArray_CountNonzero \
+ (PyArrayObject *);
+NPY_NO_EXPORT PyArray_Descr * PyArray_PromoteTypes \
+ (PyArray_Descr *, PyArray_Descr *);
+NPY_NO_EXPORT PyArray_Descr * PyArray_MinScalarType \
+ (PyArrayObject *);
+NPY_NO_EXPORT PyArray_Descr * PyArray_ResultType \
+ (npy_intp, PyArrayObject *arrs[], npy_intp, PyArray_Descr *descrs[]);
+NPY_NO_EXPORT npy_bool PyArray_CanCastArrayTo \
+ (PyArrayObject *, PyArray_Descr *, NPY_CASTING);
+NPY_NO_EXPORT npy_bool PyArray_CanCastTypeTo \
+ (PyArray_Descr *, PyArray_Descr *, NPY_CASTING);
+NPY_NO_EXPORT PyArrayObject * PyArray_EinsteinSum \
+ (char *, npy_intp, PyArrayObject **, PyArray_Descr *, NPY_ORDER, NPY_CASTING, PyArrayObject *);
+NPY_NO_EXPORT NPY_STEALS_REF_TO_ARG(3) PyObject * PyArray_NewLikeArray \
+ (PyArrayObject *, NPY_ORDER, PyArray_Descr *, int);
+NPY_NO_EXPORT int PyArray_ConvertClipmodeSequence \
+ (PyObject *, NPY_CLIPMODE *, int);
+NPY_NO_EXPORT PyObject * PyArray_MatrixProduct2 \
+ (PyObject *, PyObject *, PyArrayObject*);
+NPY_NO_EXPORT npy_bool NpyIter_IsFirstVisit \
+ (NpyIter *, int);
+NPY_NO_EXPORT NPY_STEALS_REF_TO_ARG(2) int PyArray_SetBaseObject \
+ (PyArrayObject *, PyObject *);
+NPY_NO_EXPORT void PyArray_CreateSortedStridePerm \
+ (int, npy_intp const *, npy_stride_sort_item *);
+NPY_NO_EXPORT void PyArray_RemoveAxesInPlace \
+ (PyArrayObject *, const npy_bool *);
+NPY_NO_EXPORT void PyArray_DebugPrint \
+ (PyArrayObject *);
+NPY_NO_EXPORT int PyArray_FailUnlessWriteable \
+ (PyArrayObject *, const char *);
+NPY_NO_EXPORT NPY_STEALS_REF_TO_ARG(2) int PyArray_SetUpdateIfCopyBase \
+ (PyArrayObject *, PyArrayObject *);
+NPY_NO_EXPORT void * PyDataMem_NEW \
+ (size_t);
+NPY_NO_EXPORT void PyDataMem_FREE \
+ (void *);
+NPY_NO_EXPORT void * PyDataMem_RENEW \
+ (void *, size_t);
+extern NPY_NO_EXPORT NPY_CASTING NPY_DEFAULT_ASSIGN_CASTING;
+
+NPY_NO_EXPORT int PyArray_Partition \
+ (PyArrayObject *, PyArrayObject *, int, NPY_SELECTKIND);
+NPY_NO_EXPORT PyObject * PyArray_ArgPartition \
+ (PyArrayObject *, PyArrayObject *, int, NPY_SELECTKIND);
+NPY_NO_EXPORT int PyArray_SelectkindConverter \
+ (PyObject *, NPY_SELECTKIND *);
+NPY_NO_EXPORT void * PyDataMem_NEW_ZEROED \
+ (size_t, size_t);
+NPY_NO_EXPORT int PyArray_CheckAnyScalarExact \
+ (PyObject *);
+NPY_NO_EXPORT int PyArray_ResolveWritebackIfCopy \
+ (PyArrayObject *);
+NPY_NO_EXPORT int PyArray_SetWritebackIfCopyBase \
+ (PyArrayObject *, PyArrayObject *);
+NPY_NO_EXPORT PyObject * PyDataMem_SetHandler \
+ (PyObject *);
+NPY_NO_EXPORT PyObject * PyDataMem_GetHandler \
+ (void);
+extern NPY_NO_EXPORT PyObject* PyDataMem_DefaultHandler;
+
+NPY_NO_EXPORT int NpyDatetime_ConvertDatetime64ToDatetimeStruct \
+ (PyArray_DatetimeMetaData *, npy_datetime, npy_datetimestruct *);
+NPY_NO_EXPORT int NpyDatetime_ConvertDatetimeStructToDatetime64 \
+ (PyArray_DatetimeMetaData *, const npy_datetimestruct *, npy_datetime *);
+NPY_NO_EXPORT int NpyDatetime_ConvertPyDateTimeToDatetimeStruct \
+ (PyObject *, npy_datetimestruct *, NPY_DATETIMEUNIT *, int);
+NPY_NO_EXPORT int NpyDatetime_GetDatetimeISO8601StrLen \
+ (int, NPY_DATETIMEUNIT);
+NPY_NO_EXPORT int NpyDatetime_MakeISO8601Datetime \
+ (npy_datetimestruct *, char *, npy_intp, int, int, NPY_DATETIMEUNIT, int, NPY_CASTING);
+NPY_NO_EXPORT int NpyDatetime_ParseISO8601Datetime \
+ (char const *, Py_ssize_t, NPY_DATETIMEUNIT, NPY_CASTING, npy_datetimestruct *, NPY_DATETIMEUNIT *, npy_bool *);
+NPY_NO_EXPORT int NpyString_load \
+ (npy_string_allocator *, const npy_packed_static_string *, npy_static_string *);
+NPY_NO_EXPORT int NpyString_pack \
+ (npy_string_allocator *, npy_packed_static_string *, const char *, size_t);
+NPY_NO_EXPORT int NpyString_pack_null \
+ (npy_string_allocator *, npy_packed_static_string *);
+NPY_NO_EXPORT npy_string_allocator * NpyString_acquire_allocator \
+ (const PyArray_StringDTypeObject *);
+NPY_NO_EXPORT void NpyString_acquire_allocators \
+ (size_t, PyArray_Descr *const descrs[], npy_string_allocator *allocators[]);
+NPY_NO_EXPORT void NpyString_release_allocator \
+ (npy_string_allocator *);
+NPY_NO_EXPORT void NpyString_release_allocators \
+ (size_t, npy_string_allocator *allocators[]);
+NPY_NO_EXPORT PyArray_Descr * PyArray_GetDefaultDescr \
+ (PyArray_DTypeMeta *);
+NPY_NO_EXPORT int PyArrayInitDTypeMeta_FromSpec \
+ (PyArray_DTypeMeta *, PyArrayDTypeMeta_Spec *);
+NPY_NO_EXPORT PyArray_DTypeMeta * PyArray_CommonDType \
+ (PyArray_DTypeMeta *, PyArray_DTypeMeta *);
+NPY_NO_EXPORT PyArray_DTypeMeta * PyArray_PromoteDTypeSequence \
+ (npy_intp, PyArray_DTypeMeta **);
+NPY_NO_EXPORT PyArray_ArrFuncs * _PyDataType_GetArrFuncs \
+ (const PyArray_Descr *);
+
+#else
+
+#if defined(PY_ARRAY_UNIQUE_SYMBOL)
+ #define PyArray_API PY_ARRAY_UNIQUE_SYMBOL
+ #define _NPY_VERSION_CONCAT_HELPER2(x, y) x ## y
+ #define _NPY_VERSION_CONCAT_HELPER(arg) \
+ _NPY_VERSION_CONCAT_HELPER2(arg, PyArray_RUNTIME_VERSION)
+ #define PyArray_RUNTIME_VERSION \
+ _NPY_VERSION_CONCAT_HELPER(PY_ARRAY_UNIQUE_SYMBOL)
+#endif
+
+/* By default do not export API in an .so (was never the case on windows) */
+#ifndef NPY_API_SYMBOL_ATTRIBUTE
+ #define NPY_API_SYMBOL_ATTRIBUTE NPY_VISIBILITY_HIDDEN
+#endif
+
+#if defined(NO_IMPORT) || defined(NO_IMPORT_ARRAY)
+extern NPY_API_SYMBOL_ATTRIBUTE void **PyArray_API;
+extern NPY_API_SYMBOL_ATTRIBUTE int PyArray_RUNTIME_VERSION;
+#else
+#if defined(PY_ARRAY_UNIQUE_SYMBOL)
+NPY_API_SYMBOL_ATTRIBUTE void **PyArray_API;
+NPY_API_SYMBOL_ATTRIBUTE int PyArray_RUNTIME_VERSION;
+#else
+static void **PyArray_API = NULL;
+static int PyArray_RUNTIME_VERSION = 0;
+#endif
+#endif
+
+#define PyArray_GetNDArrayCVersion \
+ (*(unsigned int (*)(void)) \
+ PyArray_API[0])
+#define PyArray_Type (*(PyTypeObject *)PyArray_API[2])
+#define PyArrayDescr_Type (*(PyTypeObject *)PyArray_API[3])
+#define PyArrayIter_Type (*(PyTypeObject *)PyArray_API[5])
+#define PyArrayMultiIter_Type (*(PyTypeObject *)PyArray_API[6])
+#define NPY_NUMUSERTYPES (*(int *)PyArray_API[7])
+#define PyBoolArrType_Type (*(PyTypeObject *)PyArray_API[8])
+#define _PyArrayScalar_BoolValues ((PyBoolScalarObject *)PyArray_API[9])
+#define PyGenericArrType_Type (*(PyTypeObject *)PyArray_API[10])
+#define PyNumberArrType_Type (*(PyTypeObject *)PyArray_API[11])
+#define PyIntegerArrType_Type (*(PyTypeObject *)PyArray_API[12])
+#define PySignedIntegerArrType_Type (*(PyTypeObject *)PyArray_API[13])
+#define PyUnsignedIntegerArrType_Type (*(PyTypeObject *)PyArray_API[14])
+#define PyInexactArrType_Type (*(PyTypeObject *)PyArray_API[15])
+#define PyFloatingArrType_Type (*(PyTypeObject *)PyArray_API[16])
+#define PyComplexFloatingArrType_Type (*(PyTypeObject *)PyArray_API[17])
+#define PyFlexibleArrType_Type (*(PyTypeObject *)PyArray_API[18])
+#define PyCharacterArrType_Type (*(PyTypeObject *)PyArray_API[19])
+#define PyByteArrType_Type (*(PyTypeObject *)PyArray_API[20])
+#define PyShortArrType_Type (*(PyTypeObject *)PyArray_API[21])
+#define PyIntArrType_Type (*(PyTypeObject *)PyArray_API[22])
+#define PyLongArrType_Type (*(PyTypeObject *)PyArray_API[23])
+#define PyLongLongArrType_Type (*(PyTypeObject *)PyArray_API[24])
+#define PyUByteArrType_Type (*(PyTypeObject *)PyArray_API[25])
+#define PyUShortArrType_Type (*(PyTypeObject *)PyArray_API[26])
+#define PyUIntArrType_Type (*(PyTypeObject *)PyArray_API[27])
+#define PyULongArrType_Type (*(PyTypeObject *)PyArray_API[28])
+#define PyULongLongArrType_Type (*(PyTypeObject *)PyArray_API[29])
+#define PyFloatArrType_Type (*(PyTypeObject *)PyArray_API[30])
+#define PyDoubleArrType_Type (*(PyTypeObject *)PyArray_API[31])
+#define PyLongDoubleArrType_Type (*(PyTypeObject *)PyArray_API[32])
+#define PyCFloatArrType_Type (*(PyTypeObject *)PyArray_API[33])
+#define PyCDoubleArrType_Type (*(PyTypeObject *)PyArray_API[34])
+#define PyCLongDoubleArrType_Type (*(PyTypeObject *)PyArray_API[35])
+#define PyObjectArrType_Type (*(PyTypeObject *)PyArray_API[36])
+#define PyStringArrType_Type (*(PyTypeObject *)PyArray_API[37])
+#define PyUnicodeArrType_Type (*(PyTypeObject *)PyArray_API[38])
+#define PyVoidArrType_Type (*(PyTypeObject *)PyArray_API[39])
+#define PyArray_INCREF \
+ (*(int (*)(PyArrayObject *)) \
+ PyArray_API[42])
+#define PyArray_XDECREF \
+ (*(int (*)(PyArrayObject *)) \
+ PyArray_API[43])
+#define PyArray_SetStringFunction \
+ (*(void (*)(PyObject *, int)) \
+ PyArray_API[44])
+#define PyArray_DescrFromType \
+ (*(PyArray_Descr * (*)(int)) \
+ PyArray_API[45])
+#define PyArray_TypeObjectFromType \
+ (*(PyObject * (*)(int)) \
+ PyArray_API[46])
+#define PyArray_Zero \
+ (*(char * (*)(PyArrayObject *)) \
+ PyArray_API[47])
+#define PyArray_One \
+ (*(char * (*)(PyArrayObject *)) \
+ PyArray_API[48])
+#define PyArray_CastToType \
+ (*(PyObject * (*)(PyArrayObject *, PyArray_Descr *, int)) \
+ PyArray_API[49])
+#define PyArray_CopyInto \
+ (*(int (*)(PyArrayObject *, PyArrayObject *)) \
+ PyArray_API[50])
+#define PyArray_CopyAnyInto \
+ (*(int (*)(PyArrayObject *, PyArrayObject *)) \
+ PyArray_API[51])
+#define PyArray_CanCastSafely \
+ (*(int (*)(int, int)) \
+ PyArray_API[52])
+#define PyArray_CanCastTo \
+ (*(npy_bool (*)(PyArray_Descr *, PyArray_Descr *)) \
+ PyArray_API[53])
+#define PyArray_ObjectType \
+ (*(int (*)(PyObject *, int)) \
+ PyArray_API[54])
+#define PyArray_DescrFromObject \
+ (*(PyArray_Descr * (*)(PyObject *, PyArray_Descr *)) \
+ PyArray_API[55])
+#define PyArray_ConvertToCommonType \
+ (*(PyArrayObject ** (*)(PyObject *, int *)) \
+ PyArray_API[56])
+#define PyArray_DescrFromScalar \
+ (*(PyArray_Descr * (*)(PyObject *)) \
+ PyArray_API[57])
+#define PyArray_DescrFromTypeObject \
+ (*(PyArray_Descr * (*)(PyObject *)) \
+ PyArray_API[58])
+#define PyArray_Size \
+ (*(npy_intp (*)(PyObject *)) \
+ PyArray_API[59])
+#define PyArray_Scalar \
+ (*(PyObject * (*)(void *, PyArray_Descr *, PyObject *)) \
+ PyArray_API[60])
+#define PyArray_FromScalar \
+ (*(PyObject * (*)(PyObject *, PyArray_Descr *)) \
+ PyArray_API[61])
+#define PyArray_ScalarAsCtype \
+ (*(void (*)(PyObject *, void *)) \
+ PyArray_API[62])
+#define PyArray_CastScalarToCtype \
+ (*(int (*)(PyObject *, void *, PyArray_Descr *)) \
+ PyArray_API[63])
+#define PyArray_CastScalarDirect \
+ (*(int (*)(PyObject *, PyArray_Descr *, void *, int)) \
+ PyArray_API[64])
+
+#if NPY_FEATURE_VERSION >= NPY_2_0_API_VERSION
+#define PyArray_Pack \
+ (*(int (*)(PyArray_Descr *, void *, PyObject *)) \
+ PyArray_API[65])
+#endif
+#define PyArray_FromAny \
+ (*(PyObject * (*)(PyObject *, PyArray_Descr *, int, int, int, PyObject *)) \
+ PyArray_API[69])
+#define PyArray_EnsureArray \
+ (*(PyObject * (*)(PyObject *)) \
+ PyArray_API[70])
+#define PyArray_EnsureAnyArray \
+ (*(PyObject * (*)(PyObject *)) \
+ PyArray_API[71])
+#define PyArray_FromFile \
+ (*(PyObject * (*)(FILE *, PyArray_Descr *, npy_intp, char *)) \
+ PyArray_API[72])
+#define PyArray_FromString \
+ (*(PyObject * (*)(char *, npy_intp, PyArray_Descr *, npy_intp, char *)) \
+ PyArray_API[73])
+#define PyArray_FromBuffer \
+ (*(PyObject * (*)(PyObject *, PyArray_Descr *, npy_intp, npy_intp)) \
+ PyArray_API[74])
+#define PyArray_FromIter \
+ (*(PyObject * (*)(PyObject *, PyArray_Descr *, npy_intp)) \
+ PyArray_API[75])
+#define PyArray_Return \
+ (*(PyObject * (*)(PyArrayObject *)) \
+ PyArray_API[76])
+#define PyArray_GetField \
+ (*(PyObject * (*)(PyArrayObject *, PyArray_Descr *, int)) \
+ PyArray_API[77])
+#define PyArray_SetField \
+ (*(int (*)(PyArrayObject *, PyArray_Descr *, int, PyObject *)) \
+ PyArray_API[78])
+#define PyArray_Byteswap \
+ (*(PyObject * (*)(PyArrayObject *, npy_bool)) \
+ PyArray_API[79])
+#define PyArray_Resize \
+ (*(PyObject * (*)(PyArrayObject *, PyArray_Dims *, int, NPY_ORDER NPY_UNUSED(order))) \
+ PyArray_API[80])
+#define PyArray_CopyObject \
+ (*(int (*)(PyArrayObject *, PyObject *)) \
+ PyArray_API[84])
+#define PyArray_NewCopy \
+ (*(PyObject * (*)(PyArrayObject *, NPY_ORDER)) \
+ PyArray_API[85])
+#define PyArray_ToList \
+ (*(PyObject * (*)(PyArrayObject *)) \
+ PyArray_API[86])
+#define PyArray_ToString \
+ (*(PyObject * (*)(PyArrayObject *, NPY_ORDER)) \
+ PyArray_API[87])
+#define PyArray_ToFile \
+ (*(int (*)(PyArrayObject *, FILE *, char *, char *)) \
+ PyArray_API[88])
+#define PyArray_Dump \
+ (*(int (*)(PyObject *, PyObject *, int)) \
+ PyArray_API[89])
+#define PyArray_Dumps \
+ (*(PyObject * (*)(PyObject *, int)) \
+ PyArray_API[90])
+#define PyArray_ValidType \
+ (*(int (*)(int)) \
+ PyArray_API[91])
+#define PyArray_UpdateFlags \
+ (*(void (*)(PyArrayObject *, int)) \
+ PyArray_API[92])
+#define PyArray_New \
+ (*(PyObject * (*)(PyTypeObject *, int, npy_intp const *, int, npy_intp const *, void *, int, int, PyObject *)) \
+ PyArray_API[93])
+#define PyArray_NewFromDescr \
+ (*(PyObject * (*)(PyTypeObject *, PyArray_Descr *, int, npy_intp const *, npy_intp const *, void *, int, PyObject *)) \
+ PyArray_API[94])
+#define PyArray_DescrNew \
+ (*(PyArray_Descr * (*)(PyArray_Descr *)) \
+ PyArray_API[95])
+#define PyArray_DescrNewFromType \
+ (*(PyArray_Descr * (*)(int)) \
+ PyArray_API[96])
+#define PyArray_GetPriority \
+ (*(double (*)(PyObject *, double)) \
+ PyArray_API[97])
+#define PyArray_IterNew \
+ (*(PyObject * (*)(PyObject *)) \
+ PyArray_API[98])
+#define PyArray_MultiIterNew \
+ (*(PyObject* (*)(int, ...)) \
+ PyArray_API[99])
+#define PyArray_PyIntAsInt \
+ (*(int (*)(PyObject *)) \
+ PyArray_API[100])
+#define PyArray_PyIntAsIntp \
+ (*(npy_intp (*)(PyObject *)) \
+ PyArray_API[101])
+#define PyArray_Broadcast \
+ (*(int (*)(PyArrayMultiIterObject *)) \
+ PyArray_API[102])
+#define PyArray_FillWithScalar \
+ (*(int (*)(PyArrayObject *, PyObject *)) \
+ PyArray_API[104])
+#define PyArray_CheckStrides \
+ (*(npy_bool (*)(int, int, npy_intp, npy_intp, npy_intp const *, npy_intp const *)) \
+ PyArray_API[105])
+#define PyArray_DescrNewByteorder \
+ (*(PyArray_Descr * (*)(PyArray_Descr *, char)) \
+ PyArray_API[106])
+#define PyArray_IterAllButAxis \
+ (*(PyObject * (*)(PyObject *, int *)) \
+ PyArray_API[107])
+#define PyArray_CheckFromAny \
+ (*(PyObject * (*)(PyObject *, PyArray_Descr *, int, int, int, PyObject *)) \
+ PyArray_API[108])
+#define PyArray_FromArray \
+ (*(PyObject * (*)(PyArrayObject *, PyArray_Descr *, int)) \
+ PyArray_API[109])
+#define PyArray_FromInterface \
+ (*(PyObject * (*)(PyObject *)) \
+ PyArray_API[110])
+#define PyArray_FromStructInterface \
+ (*(PyObject * (*)(PyObject *)) \
+ PyArray_API[111])
+#define PyArray_FromArrayAttr \
+ (*(PyObject * (*)(PyObject *, PyArray_Descr *, PyObject *)) \
+ PyArray_API[112])
+#define PyArray_ScalarKind \
+ (*(NPY_SCALARKIND (*)(int, PyArrayObject **)) \
+ PyArray_API[113])
+#define PyArray_CanCoerceScalar \
+ (*(int (*)(int, int, NPY_SCALARKIND)) \
+ PyArray_API[114])
+#define PyArray_CanCastScalar \
+ (*(npy_bool (*)(PyTypeObject *, PyTypeObject *)) \
+ PyArray_API[116])
+#define PyArray_RemoveSmallest \
+ (*(int (*)(PyArrayMultiIterObject *)) \
+ PyArray_API[118])
+#define PyArray_ElementStrides \
+ (*(int (*)(PyObject *)) \
+ PyArray_API[119])
+#define PyArray_Item_INCREF \
+ (*(void (*)(char *, PyArray_Descr *)) \
+ PyArray_API[120])
+#define PyArray_Item_XDECREF \
+ (*(void (*)(char *, PyArray_Descr *)) \
+ PyArray_API[121])
+#define PyArray_Transpose \
+ (*(PyObject * (*)(PyArrayObject *, PyArray_Dims *)) \
+ PyArray_API[123])
+#define PyArray_TakeFrom \
+ (*(PyObject * (*)(PyArrayObject *, PyObject *, int, PyArrayObject *, NPY_CLIPMODE)) \
+ PyArray_API[124])
+#define PyArray_PutTo \
+ (*(PyObject * (*)(PyArrayObject *, PyObject*, PyObject *, NPY_CLIPMODE)) \
+ PyArray_API[125])
+#define PyArray_PutMask \
+ (*(PyObject * (*)(PyArrayObject *, PyObject*, PyObject*)) \
+ PyArray_API[126])
+#define PyArray_Repeat \
+ (*(PyObject * (*)(PyArrayObject *, PyObject *, int)) \
+ PyArray_API[127])
+#define PyArray_Choose \
+ (*(PyObject * (*)(PyArrayObject *, PyObject *, PyArrayObject *, NPY_CLIPMODE)) \
+ PyArray_API[128])
+#define PyArray_Sort \
+ (*(int (*)(PyArrayObject *, int, NPY_SORTKIND)) \
+ PyArray_API[129])
+#define PyArray_ArgSort \
+ (*(PyObject * (*)(PyArrayObject *, int, NPY_SORTKIND)) \
+ PyArray_API[130])
+#define PyArray_SearchSorted \
+ (*(PyObject * (*)(PyArrayObject *, PyObject *, NPY_SEARCHSIDE, PyObject *)) \
+ PyArray_API[131])
+#define PyArray_ArgMax \
+ (*(PyObject * (*)(PyArrayObject *, int, PyArrayObject *)) \
+ PyArray_API[132])
+#define PyArray_ArgMin \
+ (*(PyObject * (*)(PyArrayObject *, int, PyArrayObject *)) \
+ PyArray_API[133])
+#define PyArray_Reshape \
+ (*(PyObject * (*)(PyArrayObject *, PyObject *)) \
+ PyArray_API[134])
+#define PyArray_Newshape \
+ (*(PyObject * (*)(PyArrayObject *, PyArray_Dims *, NPY_ORDER)) \
+ PyArray_API[135])
+#define PyArray_Squeeze \
+ (*(PyObject * (*)(PyArrayObject *)) \
+ PyArray_API[136])
+#define PyArray_View \
+ (*(PyObject * (*)(PyArrayObject *, PyArray_Descr *, PyTypeObject *)) \
+ PyArray_API[137])
+#define PyArray_SwapAxes \
+ (*(PyObject * (*)(PyArrayObject *, int, int)) \
+ PyArray_API[138])
+#define PyArray_Max \
+ (*(PyObject * (*)(PyArrayObject *, int, PyArrayObject *)) \
+ PyArray_API[139])
+#define PyArray_Min \
+ (*(PyObject * (*)(PyArrayObject *, int, PyArrayObject *)) \
+ PyArray_API[140])
+#define PyArray_Ptp \
+ (*(PyObject * (*)(PyArrayObject *, int, PyArrayObject *)) \
+ PyArray_API[141])
+#define PyArray_Mean \
+ (*(PyObject * (*)(PyArrayObject *, int, int, PyArrayObject *)) \
+ PyArray_API[142])
+#define PyArray_Trace \
+ (*(PyObject * (*)(PyArrayObject *, int, int, int, int, PyArrayObject *)) \
+ PyArray_API[143])
+#define PyArray_Diagonal \
+ (*(PyObject * (*)(PyArrayObject *, int, int, int)) \
+ PyArray_API[144])
+#define PyArray_Clip \
+ (*(PyObject * (*)(PyArrayObject *, PyObject *, PyObject *, PyArrayObject *)) \
+ PyArray_API[145])
+#define PyArray_Conjugate \
+ (*(PyObject * (*)(PyArrayObject *, PyArrayObject *)) \
+ PyArray_API[146])
+#define PyArray_Nonzero \
+ (*(PyObject * (*)(PyArrayObject *)) \
+ PyArray_API[147])
+#define PyArray_Std \
+ (*(PyObject * (*)(PyArrayObject *, int, int, PyArrayObject *, int)) \
+ PyArray_API[148])
+#define PyArray_Sum \
+ (*(PyObject * (*)(PyArrayObject *, int, int, PyArrayObject *)) \
+ PyArray_API[149])
+#define PyArray_CumSum \
+ (*(PyObject * (*)(PyArrayObject *, int, int, PyArrayObject *)) \
+ PyArray_API[150])
+#define PyArray_Prod \
+ (*(PyObject * (*)(PyArrayObject *, int, int, PyArrayObject *)) \
+ PyArray_API[151])
+#define PyArray_CumProd \
+ (*(PyObject * (*)(PyArrayObject *, int, int, PyArrayObject *)) \
+ PyArray_API[152])
+#define PyArray_All \
+ (*(PyObject * (*)(PyArrayObject *, int, PyArrayObject *)) \
+ PyArray_API[153])
+#define PyArray_Any \
+ (*(PyObject * (*)(PyArrayObject *, int, PyArrayObject *)) \
+ PyArray_API[154])
+#define PyArray_Compress \
+ (*(PyObject * (*)(PyArrayObject *, PyObject *, int, PyArrayObject *)) \
+ PyArray_API[155])
+#define PyArray_Flatten \
+ (*(PyObject * (*)(PyArrayObject *, NPY_ORDER)) \
+ PyArray_API[156])
+#define PyArray_Ravel \
+ (*(PyObject * (*)(PyArrayObject *, NPY_ORDER)) \
+ PyArray_API[157])
+#define PyArray_MultiplyList \
+ (*(npy_intp (*)(npy_intp const *, int)) \
+ PyArray_API[158])
+#define PyArray_MultiplyIntList \
+ (*(int (*)(int const *, int)) \
+ PyArray_API[159])
+#define PyArray_GetPtr \
+ (*(void * (*)(PyArrayObject *, npy_intp const*)) \
+ PyArray_API[160])
+#define PyArray_CompareLists \
+ (*(int (*)(npy_intp const *, npy_intp const *, int)) \
+ PyArray_API[161])
+#define PyArray_AsCArray \
+ (*(int (*)(PyObject **, void *, npy_intp *, int, PyArray_Descr*)) \
+ PyArray_API[162])
+#define PyArray_Free \
+ (*(int (*)(PyObject *, void *)) \
+ PyArray_API[165])
+#define PyArray_Converter \
+ (*(int (*)(PyObject *, PyObject **)) \
+ PyArray_API[166])
+#define PyArray_IntpFromSequence \
+ (*(int (*)(PyObject *, npy_intp *, int)) \
+ PyArray_API[167])
+#define PyArray_Concatenate \
+ (*(PyObject * (*)(PyObject *, int)) \
+ PyArray_API[168])
+#define PyArray_InnerProduct \
+ (*(PyObject * (*)(PyObject *, PyObject *)) \
+ PyArray_API[169])
+#define PyArray_MatrixProduct \
+ (*(PyObject * (*)(PyObject *, PyObject *)) \
+ PyArray_API[170])
+#define PyArray_Correlate \
+ (*(PyObject * (*)(PyObject *, PyObject *, int)) \
+ PyArray_API[172])
+#define PyArray_DescrConverter \
+ (*(int (*)(PyObject *, PyArray_Descr **)) \
+ PyArray_API[174])
+#define PyArray_DescrConverter2 \
+ (*(int (*)(PyObject *, PyArray_Descr **)) \
+ PyArray_API[175])
+#define PyArray_IntpConverter \
+ (*(int (*)(PyObject *, PyArray_Dims *)) \
+ PyArray_API[176])
+#define PyArray_BufferConverter \
+ (*(int (*)(PyObject *, PyArray_Chunk *)) \
+ PyArray_API[177])
+#define PyArray_AxisConverter \
+ (*(int (*)(PyObject *, int *)) \
+ PyArray_API[178])
+#define PyArray_BoolConverter \
+ (*(int (*)(PyObject *, npy_bool *)) \
+ PyArray_API[179])
+#define PyArray_ByteorderConverter \
+ (*(int (*)(PyObject *, char *)) \
+ PyArray_API[180])
+#define PyArray_OrderConverter \
+ (*(int (*)(PyObject *, NPY_ORDER *)) \
+ PyArray_API[181])
+#define PyArray_EquivTypes \
+ (*(unsigned char (*)(PyArray_Descr *, PyArray_Descr *)) \
+ PyArray_API[182])
+#define PyArray_Zeros \
+ (*(PyObject * (*)(int, npy_intp const *, PyArray_Descr *, int)) \
+ PyArray_API[183])
+#define PyArray_Empty \
+ (*(PyObject * (*)(int, npy_intp const *, PyArray_Descr *, int)) \
+ PyArray_API[184])
+#define PyArray_Where \
+ (*(PyObject * (*)(PyObject *, PyObject *, PyObject *)) \
+ PyArray_API[185])
+#define PyArray_Arange \
+ (*(PyObject * (*)(double, double, double, int)) \
+ PyArray_API[186])
+#define PyArray_ArangeObj \
+ (*(PyObject * (*)(PyObject *, PyObject *, PyObject *, PyArray_Descr *)) \
+ PyArray_API[187])
+#define PyArray_SortkindConverter \
+ (*(int (*)(PyObject *, NPY_SORTKIND *)) \
+ PyArray_API[188])
+#define PyArray_LexSort \
+ (*(PyObject * (*)(PyObject *, int)) \
+ PyArray_API[189])
+#define PyArray_Round \
+ (*(PyObject * (*)(PyArrayObject *, int, PyArrayObject *)) \
+ PyArray_API[190])
+#define PyArray_EquivTypenums \
+ (*(unsigned char (*)(int, int)) \
+ PyArray_API[191])
+#define PyArray_RegisterDataType \
+ (*(int (*)(PyArray_DescrProto *)) \
+ PyArray_API[192])
+#define PyArray_RegisterCastFunc \
+ (*(int (*)(PyArray_Descr *, int, PyArray_VectorUnaryFunc *)) \
+ PyArray_API[193])
+#define PyArray_RegisterCanCast \
+ (*(int (*)(PyArray_Descr *, int, NPY_SCALARKIND)) \
+ PyArray_API[194])
+#define PyArray_InitArrFuncs \
+ (*(void (*)(PyArray_ArrFuncs *)) \
+ PyArray_API[195])
+#define PyArray_IntTupleFromIntp \
+ (*(PyObject * (*)(int, npy_intp const *)) \
+ PyArray_API[196])
+#define PyArray_ClipmodeConverter \
+ (*(int (*)(PyObject *, NPY_CLIPMODE *)) \
+ PyArray_API[198])
+#define PyArray_OutputConverter \
+ (*(int (*)(PyObject *, PyArrayObject **)) \
+ PyArray_API[199])
+#define PyArray_BroadcastToShape \
+ (*(PyObject * (*)(PyObject *, npy_intp *, int)) \
+ PyArray_API[200])
+#define PyArray_DescrAlignConverter \
+ (*(int (*)(PyObject *, PyArray_Descr **)) \
+ PyArray_API[203])
+#define PyArray_DescrAlignConverter2 \
+ (*(int (*)(PyObject *, PyArray_Descr **)) \
+ PyArray_API[204])
+#define PyArray_SearchsideConverter \
+ (*(int (*)(PyObject *, void *)) \
+ PyArray_API[205])
+#define PyArray_CheckAxis \
+ (*(PyObject * (*)(PyArrayObject *, int *, int)) \
+ PyArray_API[206])
+#define PyArray_OverflowMultiplyList \
+ (*(npy_intp (*)(npy_intp const *, int)) \
+ PyArray_API[207])
+#define PyArray_MultiIterFromObjects \
+ (*(PyObject* (*)(PyObject **, int, int, ...)) \
+ PyArray_API[209])
+#define PyArray_GetEndianness \
+ (*(int (*)(void)) \
+ PyArray_API[210])
+#define PyArray_GetNDArrayCFeatureVersion \
+ (*(unsigned int (*)(void)) \
+ PyArray_API[211])
+#define PyArray_Correlate2 \
+ (*(PyObject * (*)(PyObject *, PyObject *, int)) \
+ PyArray_API[212])
+#define PyArray_NeighborhoodIterNew \
+ (*(PyObject* (*)(PyArrayIterObject *, const npy_intp *, int, PyArrayObject*)) \
+ PyArray_API[213])
+#define PyTimeIntegerArrType_Type (*(PyTypeObject *)PyArray_API[214])
+#define PyDatetimeArrType_Type (*(PyTypeObject *)PyArray_API[215])
+#define PyTimedeltaArrType_Type (*(PyTypeObject *)PyArray_API[216])
+#define PyHalfArrType_Type (*(PyTypeObject *)PyArray_API[217])
+#define NpyIter_Type (*(PyTypeObject *)PyArray_API[218])
+#define NpyIter_New \
+ (*(NpyIter * (*)(PyArrayObject *, npy_uint32, NPY_ORDER, NPY_CASTING, PyArray_Descr*)) \
+ PyArray_API[224])
+#define NpyIter_MultiNew \
+ (*(NpyIter * (*)(int, PyArrayObject **, npy_uint32, NPY_ORDER, NPY_CASTING, npy_uint32 *, PyArray_Descr **)) \
+ PyArray_API[225])
+#define NpyIter_AdvancedNew \
+ (*(NpyIter * (*)(int, PyArrayObject **, npy_uint32, NPY_ORDER, NPY_CASTING, npy_uint32 *, PyArray_Descr **, int, int **, npy_intp *, npy_intp)) \
+ PyArray_API[226])
+#define NpyIter_Copy \
+ (*(NpyIter * (*)(NpyIter *)) \
+ PyArray_API[227])
+#define NpyIter_Deallocate \
+ (*(int (*)(NpyIter *)) \
+ PyArray_API[228])
+#define NpyIter_HasDelayedBufAlloc \
+ (*(npy_bool (*)(NpyIter *)) \
+ PyArray_API[229])
+#define NpyIter_HasExternalLoop \
+ (*(npy_bool (*)(NpyIter *)) \
+ PyArray_API[230])
+#define NpyIter_EnableExternalLoop \
+ (*(int (*)(NpyIter *)) \
+ PyArray_API[231])
+#define NpyIter_GetInnerStrideArray \
+ (*(npy_intp * (*)(NpyIter *)) \
+ PyArray_API[232])
+#define NpyIter_GetInnerLoopSizePtr \
+ (*(npy_intp * (*)(NpyIter *)) \
+ PyArray_API[233])
+#define NpyIter_Reset \
+ (*(int (*)(NpyIter *, char **)) \
+ PyArray_API[234])
+#define NpyIter_ResetBasePointers \
+ (*(int (*)(NpyIter *, char **, char **)) \
+ PyArray_API[235])
+#define NpyIter_ResetToIterIndexRange \
+ (*(int (*)(NpyIter *, npy_intp, npy_intp, char **)) \
+ PyArray_API[236])
+#define NpyIter_GetNDim \
+ (*(int (*)(NpyIter *)) \
+ PyArray_API[237])
+#define NpyIter_GetNOp \
+ (*(int (*)(NpyIter *)) \
+ PyArray_API[238])
+#define NpyIter_GetIterNext \
+ (*(NpyIter_IterNextFunc * (*)(NpyIter *, char **)) \
+ PyArray_API[239])
+#define NpyIter_GetIterSize \
+ (*(npy_intp (*)(NpyIter *)) \
+ PyArray_API[240])
+#define NpyIter_GetIterIndexRange \
+ (*(void (*)(NpyIter *, npy_intp *, npy_intp *)) \
+ PyArray_API[241])
+#define NpyIter_GetIterIndex \
+ (*(npy_intp (*)(NpyIter *)) \
+ PyArray_API[242])
+#define NpyIter_GotoIterIndex \
+ (*(int (*)(NpyIter *, npy_intp)) \
+ PyArray_API[243])
+#define NpyIter_HasMultiIndex \
+ (*(npy_bool (*)(NpyIter *)) \
+ PyArray_API[244])
+#define NpyIter_GetShape \
+ (*(int (*)(NpyIter *, npy_intp *)) \
+ PyArray_API[245])
+#define NpyIter_GetGetMultiIndex \
+ (*(NpyIter_GetMultiIndexFunc * (*)(NpyIter *, char **)) \
+ PyArray_API[246])
+#define NpyIter_GotoMultiIndex \
+ (*(int (*)(NpyIter *, npy_intp const *)) \
+ PyArray_API[247])
+#define NpyIter_RemoveMultiIndex \
+ (*(int (*)(NpyIter *)) \
+ PyArray_API[248])
+#define NpyIter_HasIndex \
+ (*(npy_bool (*)(NpyIter *)) \
+ PyArray_API[249])
+#define NpyIter_IsBuffered \
+ (*(npy_bool (*)(NpyIter *)) \
+ PyArray_API[250])
+#define NpyIter_IsGrowInner \
+ (*(npy_bool (*)(NpyIter *)) \
+ PyArray_API[251])
+#define NpyIter_GetBufferSize \
+ (*(npy_intp (*)(NpyIter *)) \
+ PyArray_API[252])
+#define NpyIter_GetIndexPtr \
+ (*(npy_intp * (*)(NpyIter *)) \
+ PyArray_API[253])
+#define NpyIter_GotoIndex \
+ (*(int (*)(NpyIter *, npy_intp)) \
+ PyArray_API[254])
+#define NpyIter_GetDataPtrArray \
+ (*(char ** (*)(NpyIter *)) \
+ PyArray_API[255])
+#define NpyIter_GetDescrArray \
+ (*(PyArray_Descr ** (*)(NpyIter *)) \
+ PyArray_API[256])
+#define NpyIter_GetOperandArray \
+ (*(PyArrayObject ** (*)(NpyIter *)) \
+ PyArray_API[257])
+#define NpyIter_GetIterView \
+ (*(PyArrayObject * (*)(NpyIter *, npy_intp)) \
+ PyArray_API[258])
+#define NpyIter_GetReadFlags \
+ (*(void (*)(NpyIter *, char *)) \
+ PyArray_API[259])
+#define NpyIter_GetWriteFlags \
+ (*(void (*)(NpyIter *, char *)) \
+ PyArray_API[260])
+#define NpyIter_DebugPrint \
+ (*(void (*)(NpyIter *)) \
+ PyArray_API[261])
+#define NpyIter_IterationNeedsAPI \
+ (*(npy_bool (*)(NpyIter *)) \
+ PyArray_API[262])
+#define NpyIter_GetInnerFixedStrideArray \
+ (*(void (*)(NpyIter *, npy_intp *)) \
+ PyArray_API[263])
+#define NpyIter_RemoveAxis \
+ (*(int (*)(NpyIter *, int)) \
+ PyArray_API[264])
+#define NpyIter_GetAxisStrideArray \
+ (*(npy_intp * (*)(NpyIter *, int)) \
+ PyArray_API[265])
+#define NpyIter_RequiresBuffering \
+ (*(npy_bool (*)(NpyIter *)) \
+ PyArray_API[266])
+#define NpyIter_GetInitialDataPtrArray \
+ (*(char ** (*)(NpyIter *)) \
+ PyArray_API[267])
+#define NpyIter_CreateCompatibleStrides \
+ (*(int (*)(NpyIter *, npy_intp, npy_intp *)) \
+ PyArray_API[268])
+#define PyArray_CastingConverter \
+ (*(int (*)(PyObject *, NPY_CASTING *)) \
+ PyArray_API[269])
+#define PyArray_CountNonzero \
+ (*(npy_intp (*)(PyArrayObject *)) \
+ PyArray_API[270])
+#define PyArray_PromoteTypes \
+ (*(PyArray_Descr * (*)(PyArray_Descr *, PyArray_Descr *)) \
+ PyArray_API[271])
+#define PyArray_MinScalarType \
+ (*(PyArray_Descr * (*)(PyArrayObject *)) \
+ PyArray_API[272])
+#define PyArray_ResultType \
+ (*(PyArray_Descr * (*)(npy_intp, PyArrayObject *arrs[], npy_intp, PyArray_Descr *descrs[])) \
+ PyArray_API[273])
+#define PyArray_CanCastArrayTo \
+ (*(npy_bool (*)(PyArrayObject *, PyArray_Descr *, NPY_CASTING)) \
+ PyArray_API[274])
+#define PyArray_CanCastTypeTo \
+ (*(npy_bool (*)(PyArray_Descr *, PyArray_Descr *, NPY_CASTING)) \
+ PyArray_API[275])
+#define PyArray_EinsteinSum \
+ (*(PyArrayObject * (*)(char *, npy_intp, PyArrayObject **, PyArray_Descr *, NPY_ORDER, NPY_CASTING, PyArrayObject *)) \
+ PyArray_API[276])
+#define PyArray_NewLikeArray \
+ (*(PyObject * (*)(PyArrayObject *, NPY_ORDER, PyArray_Descr *, int)) \
+ PyArray_API[277])
+#define PyArray_ConvertClipmodeSequence \
+ (*(int (*)(PyObject *, NPY_CLIPMODE *, int)) \
+ PyArray_API[279])
+#define PyArray_MatrixProduct2 \
+ (*(PyObject * (*)(PyObject *, PyObject *, PyArrayObject*)) \
+ PyArray_API[280])
+#define NpyIter_IsFirstVisit \
+ (*(npy_bool (*)(NpyIter *, int)) \
+ PyArray_API[281])
+#define PyArray_SetBaseObject \
+ (*(int (*)(PyArrayObject *, PyObject *)) \
+ PyArray_API[282])
+#define PyArray_CreateSortedStridePerm \
+ (*(void (*)(int, npy_intp const *, npy_stride_sort_item *)) \
+ PyArray_API[283])
+#define PyArray_RemoveAxesInPlace \
+ (*(void (*)(PyArrayObject *, const npy_bool *)) \
+ PyArray_API[284])
+#define PyArray_DebugPrint \
+ (*(void (*)(PyArrayObject *)) \
+ PyArray_API[285])
+#define PyArray_FailUnlessWriteable \
+ (*(int (*)(PyArrayObject *, const char *)) \
+ PyArray_API[286])
+#define PyArray_SetUpdateIfCopyBase \
+ (*(int (*)(PyArrayObject *, PyArrayObject *)) \
+ PyArray_API[287])
+#define PyDataMem_NEW \
+ (*(void * (*)(size_t)) \
+ PyArray_API[288])
+#define PyDataMem_FREE \
+ (*(void (*)(void *)) \
+ PyArray_API[289])
+#define PyDataMem_RENEW \
+ (*(void * (*)(void *, size_t)) \
+ PyArray_API[290])
+#define NPY_DEFAULT_ASSIGN_CASTING (*(NPY_CASTING *)PyArray_API[292])
+#define PyArray_Partition \
+ (*(int (*)(PyArrayObject *, PyArrayObject *, int, NPY_SELECTKIND)) \
+ PyArray_API[296])
+#define PyArray_ArgPartition \
+ (*(PyObject * (*)(PyArrayObject *, PyArrayObject *, int, NPY_SELECTKIND)) \
+ PyArray_API[297])
+#define PyArray_SelectkindConverter \
+ (*(int (*)(PyObject *, NPY_SELECTKIND *)) \
+ PyArray_API[298])
+#define PyDataMem_NEW_ZEROED \
+ (*(void * (*)(size_t, size_t)) \
+ PyArray_API[299])
+#define PyArray_CheckAnyScalarExact \
+ (*(int (*)(PyObject *)) \
+ PyArray_API[300])
+#define PyArray_ResolveWritebackIfCopy \
+ (*(int (*)(PyArrayObject *)) \
+ PyArray_API[302])
+#define PyArray_SetWritebackIfCopyBase \
+ (*(int (*)(PyArrayObject *, PyArrayObject *)) \
+ PyArray_API[303])
+
+#if NPY_FEATURE_VERSION >= NPY_1_22_API_VERSION
+#define PyDataMem_SetHandler \
+ (*(PyObject * (*)(PyObject *)) \
+ PyArray_API[304])
+#endif
+
+#if NPY_FEATURE_VERSION >= NPY_1_22_API_VERSION
+#define PyDataMem_GetHandler \
+ (*(PyObject * (*)(void)) \
+ PyArray_API[305])
+#endif
+#define PyDataMem_DefaultHandler (*(PyObject* *)PyArray_API[306])
+
+#if NPY_FEATURE_VERSION >= NPY_2_0_API_VERSION
+#define NpyDatetime_ConvertDatetime64ToDatetimeStruct \
+ (*(int (*)(PyArray_DatetimeMetaData *, npy_datetime, npy_datetimestruct *)) \
+ PyArray_API[307])
+#endif
+
+#if NPY_FEATURE_VERSION >= NPY_2_0_API_VERSION
+#define NpyDatetime_ConvertDatetimeStructToDatetime64 \
+ (*(int (*)(PyArray_DatetimeMetaData *, const npy_datetimestruct *, npy_datetime *)) \
+ PyArray_API[308])
+#endif
+
+#if NPY_FEATURE_VERSION >= NPY_2_0_API_VERSION
+#define NpyDatetime_ConvertPyDateTimeToDatetimeStruct \
+ (*(int (*)(PyObject *, npy_datetimestruct *, NPY_DATETIMEUNIT *, int)) \
+ PyArray_API[309])
+#endif
+
+#if NPY_FEATURE_VERSION >= NPY_2_0_API_VERSION
+#define NpyDatetime_GetDatetimeISO8601StrLen \
+ (*(int (*)(int, NPY_DATETIMEUNIT)) \
+ PyArray_API[310])
+#endif
+
+#if NPY_FEATURE_VERSION >= NPY_2_0_API_VERSION
+#define NpyDatetime_MakeISO8601Datetime \
+ (*(int (*)(npy_datetimestruct *, char *, npy_intp, int, int, NPY_DATETIMEUNIT, int, NPY_CASTING)) \
+ PyArray_API[311])
+#endif
+
+#if NPY_FEATURE_VERSION >= NPY_2_0_API_VERSION
+#define NpyDatetime_ParseISO8601Datetime \
+ (*(int (*)(char const *, Py_ssize_t, NPY_DATETIMEUNIT, NPY_CASTING, npy_datetimestruct *, NPY_DATETIMEUNIT *, npy_bool *)) \
+ PyArray_API[312])
+#endif
+
+#if NPY_FEATURE_VERSION >= NPY_2_0_API_VERSION
+#define NpyString_load \
+ (*(int (*)(npy_string_allocator *, const npy_packed_static_string *, npy_static_string *)) \
+ PyArray_API[313])
+#endif
+
+#if NPY_FEATURE_VERSION >= NPY_2_0_API_VERSION
+#define NpyString_pack \
+ (*(int (*)(npy_string_allocator *, npy_packed_static_string *, const char *, size_t)) \
+ PyArray_API[314])
+#endif
+
+#if NPY_FEATURE_VERSION >= NPY_2_0_API_VERSION
+#define NpyString_pack_null \
+ (*(int (*)(npy_string_allocator *, npy_packed_static_string *)) \
+ PyArray_API[315])
+#endif
+
+#if NPY_FEATURE_VERSION >= NPY_2_0_API_VERSION
+#define NpyString_acquire_allocator \
+ (*(npy_string_allocator * (*)(const PyArray_StringDTypeObject *)) \
+ PyArray_API[316])
+#endif
+
+#if NPY_FEATURE_VERSION >= NPY_2_0_API_VERSION
+#define NpyString_acquire_allocators \
+ (*(void (*)(size_t, PyArray_Descr *const descrs[], npy_string_allocator *allocators[])) \
+ PyArray_API[317])
+#endif
+
+#if NPY_FEATURE_VERSION >= NPY_2_0_API_VERSION
+#define NpyString_release_allocator \
+ (*(void (*)(npy_string_allocator *)) \
+ PyArray_API[318])
+#endif
+
+#if NPY_FEATURE_VERSION >= NPY_2_0_API_VERSION
+#define NpyString_release_allocators \
+ (*(void (*)(size_t, npy_string_allocator *allocators[])) \
+ PyArray_API[319])
+#endif
+
+#if NPY_FEATURE_VERSION >= NPY_2_0_API_VERSION
+#define PyArray_GetDefaultDescr \
+ (*(PyArray_Descr * (*)(PyArray_DTypeMeta *)) \
+ PyArray_API[361])
+#endif
+
+#if NPY_FEATURE_VERSION >= NPY_2_0_API_VERSION
+#define PyArrayInitDTypeMeta_FromSpec \
+ (*(int (*)(PyArray_DTypeMeta *, PyArrayDTypeMeta_Spec *)) \
+ PyArray_API[362])
+#endif
+
+#if NPY_FEATURE_VERSION >= NPY_2_0_API_VERSION
+#define PyArray_CommonDType \
+ (*(PyArray_DTypeMeta * (*)(PyArray_DTypeMeta *, PyArray_DTypeMeta *)) \
+ PyArray_API[363])
+#endif
+
+#if NPY_FEATURE_VERSION >= NPY_2_0_API_VERSION
+#define PyArray_PromoteDTypeSequence \
+ (*(PyArray_DTypeMeta * (*)(npy_intp, PyArray_DTypeMeta **)) \
+ PyArray_API[364])
+#endif
+#define _PyDataType_GetArrFuncs \
+ (*(PyArray_ArrFuncs * (*)(const PyArray_Descr *)) \
+ PyArray_API[365])
+
+/*
+ * The DType classes are inconvenient for the Python generation so exposed
+ * manually in the header below (may be moved).
+ */
+#include "numpy/_public_dtype_api_table.h"
+
+#if !defined(NO_IMPORT_ARRAY) && !defined(NO_IMPORT)
+static int
+_import_array(void)
+{
+ int st;
+ PyObject *numpy = PyImport_ImportModule("numpy._core._multiarray_umath");
+ if (numpy == NULL && PyErr_ExceptionMatches(PyExc_ModuleNotFoundError)) {
+ PyErr_Clear();
+ numpy = PyImport_ImportModule("numpy.core._multiarray_umath");
+ }
+
+ if (numpy == NULL) {
+ return -1;
+ }
+
+ PyObject *c_api = PyObject_GetAttrString(numpy, "_ARRAY_API");
+ Py_DECREF(numpy);
+ if (c_api == NULL) {
+ return -1;
+ }
+
+ if (!PyCapsule_CheckExact(c_api)) {
+ PyErr_SetString(PyExc_RuntimeError, "_ARRAY_API is not PyCapsule object");
+ Py_DECREF(c_api);
+ return -1;
+ }
+ PyArray_API = (void **)PyCapsule_GetPointer(c_api, NULL);
+ Py_DECREF(c_api);
+ if (PyArray_API == NULL) {
+ PyErr_SetString(PyExc_RuntimeError, "_ARRAY_API is NULL pointer");
+ return -1;
+ }
+
+ /*
+ * On exceedingly few platforms these sizes may not match, in which case
+ * We do not support older NumPy versions at all.
+ */
+ if (sizeof(Py_ssize_t) != sizeof(Py_intptr_t) &&
+ PyArray_RUNTIME_VERSION < NPY_2_0_API_VERSION) {
+ PyErr_Format(PyExc_RuntimeError,
+ "module compiled against NumPy 2.0 but running on NumPy 1.x. "
+ "Unfortunately, this is not supported on niche platforms where "
+ "`sizeof(size_t) != sizeof(inptr_t)`.");
+ }
+ /*
+ * Perform runtime check of C API version. As of now NumPy 2.0 is ABI
+ * backwards compatible (in the exposed feature subset!) for all practical
+ * purposes.
+ */
+ if (NPY_VERSION < PyArray_GetNDArrayCVersion()) {
+ PyErr_Format(PyExc_RuntimeError, "module compiled against "\
+ "ABI version 0x%x but this version of numpy is 0x%x", \
+ (int) NPY_VERSION, (int) PyArray_GetNDArrayCVersion());
+ return -1;
+ }
+ PyArray_RUNTIME_VERSION = (int)PyArray_GetNDArrayCFeatureVersion();
+ if (NPY_FEATURE_VERSION > PyArray_RUNTIME_VERSION) {
+ PyErr_Format(PyExc_RuntimeError,
+ "module was compiled against NumPy C-API version 0x%x "
+ "(NumPy " NPY_FEATURE_VERSION_STRING ") "
+ "but the running NumPy has C-API version 0x%x. "
+ "Check the section C-API incompatibility at the "
+ "Troubleshooting ImportError section at "
+ "https://numpy.org/devdocs/user/troubleshooting-importerror.html"
+ "#c-api-incompatibility "
+ "for indications on how to solve this problem.",
+ (int)NPY_FEATURE_VERSION, PyArray_RUNTIME_VERSION);
+ return -1;
+ }
+
+ /*
+ * Perform runtime check of endianness and check it matches the one set by
+ * the headers (npy_endian.h) as a safeguard
+ */
+ st = PyArray_GetEndianness();
+ if (st == NPY_CPU_UNKNOWN_ENDIAN) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "FATAL: module compiled as unknown endian");
+ return -1;
+ }
+#if NPY_BYTE_ORDER == NPY_BIG_ENDIAN
+ if (st != NPY_CPU_BIG) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "FATAL: module compiled as big endian, but "
+ "detected different endianness at runtime");
+ return -1;
+ }
+#elif NPY_BYTE_ORDER == NPY_LITTLE_ENDIAN
+ if (st != NPY_CPU_LITTLE) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "FATAL: module compiled as little endian, but "
+ "detected different endianness at runtime");
+ return -1;
+ }
+#endif
+
+ return 0;
+}
+
+#define import_array() { \
+ if (_import_array() < 0) { \
+ PyErr_Print(); \
+ PyErr_SetString( \
+ PyExc_ImportError, \
+ "numpy._core.multiarray failed to import" \
+ ); \
+ return NULL; \
+ } \
+}
+
+#define import_array1(ret) { \
+ if (_import_array() < 0) { \
+ PyErr_Print(); \
+ PyErr_SetString( \
+ PyExc_ImportError, \
+ "numpy._core.multiarray failed to import" \
+ ); \
+ return ret; \
+ } \
+}
+
+#define import_array2(msg, ret) { \
+ if (_import_array() < 0) { \
+ PyErr_Print(); \
+ PyErr_SetString(PyExc_ImportError, msg); \
+ return ret; \
+ } \
+}
+
+#endif
+
+#endif
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/__ufunc_api.c b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/__ufunc_api.c
new file mode 100644
index 0000000000000000000000000000000000000000..10fcbc4553989057667a90ce9d587deefc13f5f1
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/__ufunc_api.c
@@ -0,0 +1,54 @@
+
+/* These pointers will be stored in the C-object for use in other
+ extension modules
+*/
+
+void *PyUFunc_API[] = {
+ (void *) &PyUFunc_Type,
+ (void *) PyUFunc_FromFuncAndData,
+ (void *) PyUFunc_RegisterLoopForType,
+ NULL,
+ (void *) PyUFunc_f_f_As_d_d,
+ (void *) PyUFunc_d_d,
+ (void *) PyUFunc_f_f,
+ (void *) PyUFunc_g_g,
+ (void *) PyUFunc_F_F_As_D_D,
+ (void *) PyUFunc_F_F,
+ (void *) PyUFunc_D_D,
+ (void *) PyUFunc_G_G,
+ (void *) PyUFunc_O_O,
+ (void *) PyUFunc_ff_f_As_dd_d,
+ (void *) PyUFunc_ff_f,
+ (void *) PyUFunc_dd_d,
+ (void *) PyUFunc_gg_g,
+ (void *) PyUFunc_FF_F_As_DD_D,
+ (void *) PyUFunc_DD_D,
+ (void *) PyUFunc_FF_F,
+ (void *) PyUFunc_GG_G,
+ (void *) PyUFunc_OO_O,
+ (void *) PyUFunc_O_O_method,
+ (void *) PyUFunc_OO_O_method,
+ (void *) PyUFunc_On_Om,
+ NULL,
+ NULL,
+ (void *) PyUFunc_clearfperr,
+ (void *) PyUFunc_getfperr,
+ NULL,
+ (void *) PyUFunc_ReplaceLoopBySignature,
+ (void *) PyUFunc_FromFuncAndDataAndSignature,
+ NULL,
+ (void *) PyUFunc_e_e,
+ (void *) PyUFunc_e_e_As_f_f,
+ (void *) PyUFunc_e_e_As_d_d,
+ (void *) PyUFunc_ee_e,
+ (void *) PyUFunc_ee_e_As_ff_f,
+ (void *) PyUFunc_ee_e_As_dd_d,
+ (void *) PyUFunc_DefaultTypeResolver,
+ (void *) PyUFunc_ValidateCasting,
+ (void *) PyUFunc_RegisterLoopForDescr,
+ (void *) PyUFunc_FromFuncAndDataAndSignatureAndIdentity,
+ (void *) PyUFunc_AddLoopFromSpec,
+ (void *) PyUFunc_AddPromoter,
+ (void *) PyUFunc_AddWrappingLoop,
+ (void *) PyUFunc_GiveFloatingpointErrors
+};
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/__ufunc_api.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/__ufunc_api.h
new file mode 100644
index 0000000000000000000000000000000000000000..df7ded10b548d495338dc368d727cf77ff70740a
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/__ufunc_api.h
@@ -0,0 +1,340 @@
+
+#ifdef _UMATHMODULE
+
+extern NPY_NO_EXPORT PyTypeObject PyUFunc_Type;
+
+extern NPY_NO_EXPORT PyTypeObject PyUFunc_Type;
+
+NPY_NO_EXPORT PyObject * PyUFunc_FromFuncAndData \
+ (PyUFuncGenericFunction *, void *const *, const char *, int, int, int, int, const char *, const char *, int);
+NPY_NO_EXPORT int PyUFunc_RegisterLoopForType \
+ (PyUFuncObject *, int, PyUFuncGenericFunction, const int *, void *);
+NPY_NO_EXPORT void PyUFunc_f_f_As_d_d \
+ (char **, npy_intp const *, npy_intp const *, void *);
+NPY_NO_EXPORT void PyUFunc_d_d \
+ (char **, npy_intp const *, npy_intp const *, void *);
+NPY_NO_EXPORT void PyUFunc_f_f \
+ (char **, npy_intp const *, npy_intp const *, void *);
+NPY_NO_EXPORT void PyUFunc_g_g \
+ (char **, npy_intp const *, npy_intp const *, void *);
+NPY_NO_EXPORT void PyUFunc_F_F_As_D_D \
+ (char **, npy_intp const *, npy_intp const *, void *);
+NPY_NO_EXPORT void PyUFunc_F_F \
+ (char **, npy_intp const *, npy_intp const *, void *);
+NPY_NO_EXPORT void PyUFunc_D_D \
+ (char **, npy_intp const *, npy_intp const *, void *);
+NPY_NO_EXPORT void PyUFunc_G_G \
+ (char **, npy_intp const *, npy_intp const *, void *);
+NPY_NO_EXPORT void PyUFunc_O_O \
+ (char **, npy_intp const *, npy_intp const *, void *);
+NPY_NO_EXPORT void PyUFunc_ff_f_As_dd_d \
+ (char **, npy_intp const *, npy_intp const *, void *);
+NPY_NO_EXPORT void PyUFunc_ff_f \
+ (char **, npy_intp const *, npy_intp const *, void *);
+NPY_NO_EXPORT void PyUFunc_dd_d \
+ (char **, npy_intp const *, npy_intp const *, void *);
+NPY_NO_EXPORT void PyUFunc_gg_g \
+ (char **, npy_intp const *, npy_intp const *, void *);
+NPY_NO_EXPORT void PyUFunc_FF_F_As_DD_D \
+ (char **, npy_intp const *, npy_intp const *, void *);
+NPY_NO_EXPORT void PyUFunc_DD_D \
+ (char **, npy_intp const *, npy_intp const *, void *);
+NPY_NO_EXPORT void PyUFunc_FF_F \
+ (char **, npy_intp const *, npy_intp const *, void *);
+NPY_NO_EXPORT void PyUFunc_GG_G \
+ (char **, npy_intp const *, npy_intp const *, void *);
+NPY_NO_EXPORT void PyUFunc_OO_O \
+ (char **, npy_intp const *, npy_intp const *, void *);
+NPY_NO_EXPORT void PyUFunc_O_O_method \
+ (char **, npy_intp const *, npy_intp const *, void *);
+NPY_NO_EXPORT void PyUFunc_OO_O_method \
+ (char **, npy_intp const *, npy_intp const *, void *);
+NPY_NO_EXPORT void PyUFunc_On_Om \
+ (char **, npy_intp const *, npy_intp const *, void *);
+NPY_NO_EXPORT void PyUFunc_clearfperr \
+ (void);
+NPY_NO_EXPORT int PyUFunc_getfperr \
+ (void);
+NPY_NO_EXPORT int PyUFunc_ReplaceLoopBySignature \
+ (PyUFuncObject *, PyUFuncGenericFunction, const int *, PyUFuncGenericFunction *);
+NPY_NO_EXPORT PyObject * PyUFunc_FromFuncAndDataAndSignature \
+ (PyUFuncGenericFunction *, void *const *, const char *, int, int, int, int, const char *, const char *, int, const char *);
+NPY_NO_EXPORT void PyUFunc_e_e \
+ (char **, npy_intp const *, npy_intp const *, void *);
+NPY_NO_EXPORT void PyUFunc_e_e_As_f_f \
+ (char **, npy_intp const *, npy_intp const *, void *);
+NPY_NO_EXPORT void PyUFunc_e_e_As_d_d \
+ (char **, npy_intp const *, npy_intp const *, void *);
+NPY_NO_EXPORT void PyUFunc_ee_e \
+ (char **, npy_intp const *, npy_intp const *, void *);
+NPY_NO_EXPORT void PyUFunc_ee_e_As_ff_f \
+ (char **, npy_intp const *, npy_intp const *, void *);
+NPY_NO_EXPORT void PyUFunc_ee_e_As_dd_d \
+ (char **, npy_intp const *, npy_intp const *, void *);
+NPY_NO_EXPORT int PyUFunc_DefaultTypeResolver \
+ (PyUFuncObject *, NPY_CASTING, PyArrayObject **, PyObject *, PyArray_Descr **);
+NPY_NO_EXPORT int PyUFunc_ValidateCasting \
+ (PyUFuncObject *, NPY_CASTING, PyArrayObject **, PyArray_Descr *const *);
+NPY_NO_EXPORT int PyUFunc_RegisterLoopForDescr \
+ (PyUFuncObject *, PyArray_Descr *, PyUFuncGenericFunction, PyArray_Descr **, void *);
+NPY_NO_EXPORT PyObject * PyUFunc_FromFuncAndDataAndSignatureAndIdentity \
+ (PyUFuncGenericFunction *, void *const *, const char *, int, int, int, int, const char *, const char *, const int, const char *, PyObject *);
+NPY_NO_EXPORT int PyUFunc_AddLoopFromSpec \
+ (PyObject *, PyArrayMethod_Spec *);
+NPY_NO_EXPORT int PyUFunc_AddPromoter \
+ (PyObject *, PyObject *, PyObject *);
+NPY_NO_EXPORT int PyUFunc_AddWrappingLoop \
+ (PyObject *, PyArray_DTypeMeta *new_dtypes[], PyArray_DTypeMeta *wrapped_dtypes[], PyArrayMethod_TranslateGivenDescriptors *, PyArrayMethod_TranslateLoopDescriptors *);
+NPY_NO_EXPORT int PyUFunc_GiveFloatingpointErrors \
+ (const char *, int);
+
+#else
+
+#if defined(PY_UFUNC_UNIQUE_SYMBOL)
+#define PyUFunc_API PY_UFUNC_UNIQUE_SYMBOL
+#endif
+
+/* By default do not export API in an .so (was never the case on windows) */
+#ifndef NPY_API_SYMBOL_ATTRIBUTE
+ #define NPY_API_SYMBOL_ATTRIBUTE NPY_VISIBILITY_HIDDEN
+#endif
+
+#if defined(NO_IMPORT) || defined(NO_IMPORT_UFUNC)
+extern NPY_API_SYMBOL_ATTRIBUTE void **PyUFunc_API;
+#else
+#if defined(PY_UFUNC_UNIQUE_SYMBOL)
+NPY_API_SYMBOL_ATTRIBUTE void **PyUFunc_API;
+#else
+static void **PyUFunc_API=NULL;
+#endif
+#endif
+
+#define PyUFunc_Type (*(PyTypeObject *)PyUFunc_API[0])
+#define PyUFunc_FromFuncAndData \
+ (*(PyObject * (*)(PyUFuncGenericFunction *, void *const *, const char *, int, int, int, int, const char *, const char *, int)) \
+ PyUFunc_API[1])
+#define PyUFunc_RegisterLoopForType \
+ (*(int (*)(PyUFuncObject *, int, PyUFuncGenericFunction, const int *, void *)) \
+ PyUFunc_API[2])
+#define PyUFunc_f_f_As_d_d \
+ (*(void (*)(char **, npy_intp const *, npy_intp const *, void *)) \
+ PyUFunc_API[4])
+#define PyUFunc_d_d \
+ (*(void (*)(char **, npy_intp const *, npy_intp const *, void *)) \
+ PyUFunc_API[5])
+#define PyUFunc_f_f \
+ (*(void (*)(char **, npy_intp const *, npy_intp const *, void *)) \
+ PyUFunc_API[6])
+#define PyUFunc_g_g \
+ (*(void (*)(char **, npy_intp const *, npy_intp const *, void *)) \
+ PyUFunc_API[7])
+#define PyUFunc_F_F_As_D_D \
+ (*(void (*)(char **, npy_intp const *, npy_intp const *, void *)) \
+ PyUFunc_API[8])
+#define PyUFunc_F_F \
+ (*(void (*)(char **, npy_intp const *, npy_intp const *, void *)) \
+ PyUFunc_API[9])
+#define PyUFunc_D_D \
+ (*(void (*)(char **, npy_intp const *, npy_intp const *, void *)) \
+ PyUFunc_API[10])
+#define PyUFunc_G_G \
+ (*(void (*)(char **, npy_intp const *, npy_intp const *, void *)) \
+ PyUFunc_API[11])
+#define PyUFunc_O_O \
+ (*(void (*)(char **, npy_intp const *, npy_intp const *, void *)) \
+ PyUFunc_API[12])
+#define PyUFunc_ff_f_As_dd_d \
+ (*(void (*)(char **, npy_intp const *, npy_intp const *, void *)) \
+ PyUFunc_API[13])
+#define PyUFunc_ff_f \
+ (*(void (*)(char **, npy_intp const *, npy_intp const *, void *)) \
+ PyUFunc_API[14])
+#define PyUFunc_dd_d \
+ (*(void (*)(char **, npy_intp const *, npy_intp const *, void *)) \
+ PyUFunc_API[15])
+#define PyUFunc_gg_g \
+ (*(void (*)(char **, npy_intp const *, npy_intp const *, void *)) \
+ PyUFunc_API[16])
+#define PyUFunc_FF_F_As_DD_D \
+ (*(void (*)(char **, npy_intp const *, npy_intp const *, void *)) \
+ PyUFunc_API[17])
+#define PyUFunc_DD_D \
+ (*(void (*)(char **, npy_intp const *, npy_intp const *, void *)) \
+ PyUFunc_API[18])
+#define PyUFunc_FF_F \
+ (*(void (*)(char **, npy_intp const *, npy_intp const *, void *)) \
+ PyUFunc_API[19])
+#define PyUFunc_GG_G \
+ (*(void (*)(char **, npy_intp const *, npy_intp const *, void *)) \
+ PyUFunc_API[20])
+#define PyUFunc_OO_O \
+ (*(void (*)(char **, npy_intp const *, npy_intp const *, void *)) \
+ PyUFunc_API[21])
+#define PyUFunc_O_O_method \
+ (*(void (*)(char **, npy_intp const *, npy_intp const *, void *)) \
+ PyUFunc_API[22])
+#define PyUFunc_OO_O_method \
+ (*(void (*)(char **, npy_intp const *, npy_intp const *, void *)) \
+ PyUFunc_API[23])
+#define PyUFunc_On_Om \
+ (*(void (*)(char **, npy_intp const *, npy_intp const *, void *)) \
+ PyUFunc_API[24])
+#define PyUFunc_clearfperr \
+ (*(void (*)(void)) \
+ PyUFunc_API[27])
+#define PyUFunc_getfperr \
+ (*(int (*)(void)) \
+ PyUFunc_API[28])
+#define PyUFunc_ReplaceLoopBySignature \
+ (*(int (*)(PyUFuncObject *, PyUFuncGenericFunction, const int *, PyUFuncGenericFunction *)) \
+ PyUFunc_API[30])
+#define PyUFunc_FromFuncAndDataAndSignature \
+ (*(PyObject * (*)(PyUFuncGenericFunction *, void *const *, const char *, int, int, int, int, const char *, const char *, int, const char *)) \
+ PyUFunc_API[31])
+#define PyUFunc_e_e \
+ (*(void (*)(char **, npy_intp const *, npy_intp const *, void *)) \
+ PyUFunc_API[33])
+#define PyUFunc_e_e_As_f_f \
+ (*(void (*)(char **, npy_intp const *, npy_intp const *, void *)) \
+ PyUFunc_API[34])
+#define PyUFunc_e_e_As_d_d \
+ (*(void (*)(char **, npy_intp const *, npy_intp const *, void *)) \
+ PyUFunc_API[35])
+#define PyUFunc_ee_e \
+ (*(void (*)(char **, npy_intp const *, npy_intp const *, void *)) \
+ PyUFunc_API[36])
+#define PyUFunc_ee_e_As_ff_f \
+ (*(void (*)(char **, npy_intp const *, npy_intp const *, void *)) \
+ PyUFunc_API[37])
+#define PyUFunc_ee_e_As_dd_d \
+ (*(void (*)(char **, npy_intp const *, npy_intp const *, void *)) \
+ PyUFunc_API[38])
+#define PyUFunc_DefaultTypeResolver \
+ (*(int (*)(PyUFuncObject *, NPY_CASTING, PyArrayObject **, PyObject *, PyArray_Descr **)) \
+ PyUFunc_API[39])
+#define PyUFunc_ValidateCasting \
+ (*(int (*)(PyUFuncObject *, NPY_CASTING, PyArrayObject **, PyArray_Descr *const *)) \
+ PyUFunc_API[40])
+#define PyUFunc_RegisterLoopForDescr \
+ (*(int (*)(PyUFuncObject *, PyArray_Descr *, PyUFuncGenericFunction, PyArray_Descr **, void *)) \
+ PyUFunc_API[41])
+
+#if NPY_FEATURE_VERSION >= NPY_1_16_API_VERSION
+#define PyUFunc_FromFuncAndDataAndSignatureAndIdentity \
+ (*(PyObject * (*)(PyUFuncGenericFunction *, void *const *, const char *, int, int, int, int, const char *, const char *, const int, const char *, PyObject *)) \
+ PyUFunc_API[42])
+#endif
+
+#if NPY_FEATURE_VERSION >= NPY_2_0_API_VERSION
+#define PyUFunc_AddLoopFromSpec \
+ (*(int (*)(PyObject *, PyArrayMethod_Spec *)) \
+ PyUFunc_API[43])
+#endif
+
+#if NPY_FEATURE_VERSION >= NPY_2_0_API_VERSION
+#define PyUFunc_AddPromoter \
+ (*(int (*)(PyObject *, PyObject *, PyObject *)) \
+ PyUFunc_API[44])
+#endif
+
+#if NPY_FEATURE_VERSION >= NPY_2_0_API_VERSION
+#define PyUFunc_AddWrappingLoop \
+ (*(int (*)(PyObject *, PyArray_DTypeMeta *new_dtypes[], PyArray_DTypeMeta *wrapped_dtypes[], PyArrayMethod_TranslateGivenDescriptors *, PyArrayMethod_TranslateLoopDescriptors *)) \
+ PyUFunc_API[45])
+#endif
+
+#if NPY_FEATURE_VERSION >= NPY_2_0_API_VERSION
+#define PyUFunc_GiveFloatingpointErrors \
+ (*(int (*)(const char *, int)) \
+ PyUFunc_API[46])
+#endif
+
+static inline int
+_import_umath(void)
+{
+ PyObject *numpy = PyImport_ImportModule("numpy._core._multiarray_umath");
+ if (numpy == NULL && PyErr_ExceptionMatches(PyExc_ModuleNotFoundError)) {
+ PyErr_Clear();
+ numpy = PyImport_ImportModule("numpy.core._multiarray_umath");
+ }
+
+ if (numpy == NULL) {
+ PyErr_SetString(PyExc_ImportError,
+ "_multiarray_umath failed to import");
+ return -1;
+ }
+
+ PyObject *c_api = PyObject_GetAttrString(numpy, "_UFUNC_API");
+ Py_DECREF(numpy);
+ if (c_api == NULL) {
+ PyErr_SetString(PyExc_AttributeError, "_UFUNC_API not found");
+ return -1;
+ }
+
+ if (!PyCapsule_CheckExact(c_api)) {
+ PyErr_SetString(PyExc_RuntimeError, "_UFUNC_API is not PyCapsule object");
+ Py_DECREF(c_api);
+ return -1;
+ }
+ PyUFunc_API = (void **)PyCapsule_GetPointer(c_api, NULL);
+ Py_DECREF(c_api);
+ if (PyUFunc_API == NULL) {
+ PyErr_SetString(PyExc_RuntimeError, "_UFUNC_API is NULL pointer");
+ return -1;
+ }
+ return 0;
+}
+
+#define import_umath() \
+ do {\
+ UFUNC_NOFPE\
+ if (_import_umath() < 0) {\
+ PyErr_Print();\
+ PyErr_SetString(PyExc_ImportError,\
+ "numpy._core.umath failed to import");\
+ return NULL;\
+ }\
+ } while(0)
+
+#define import_umath1(ret) \
+ do {\
+ UFUNC_NOFPE\
+ if (_import_umath() < 0) {\
+ PyErr_Print();\
+ PyErr_SetString(PyExc_ImportError,\
+ "numpy._core.umath failed to import");\
+ return ret;\
+ }\
+ } while(0)
+
+#define import_umath2(ret, msg) \
+ do {\
+ UFUNC_NOFPE\
+ if (_import_umath() < 0) {\
+ PyErr_Print();\
+ PyErr_SetString(PyExc_ImportError, msg);\
+ return ret;\
+ }\
+ } while(0)
+
+#define import_ufunc() \
+ do {\
+ UFUNC_NOFPE\
+ if (_import_umath() < 0) {\
+ PyErr_Print();\
+ PyErr_SetString(PyExc_ImportError,\
+ "numpy._core.umath failed to import");\
+ }\
+ } while(0)
+
+
+static inline int
+PyUFunc_ImportUFuncAPI()
+{
+ if (NPY_UNLIKELY(PyUFunc_API == NULL)) {
+ import_umath1(-1);
+ }
+ return 0;
+}
+
+#endif
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/_neighborhood_iterator_imp.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/_neighborhood_iterator_imp.h
new file mode 100644
index 0000000000000000000000000000000000000000..b365cb50854f381f1a399b7aea2adab846490366
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/_neighborhood_iterator_imp.h
@@ -0,0 +1,90 @@
+#ifndef NUMPY_CORE_INCLUDE_NUMPY__NEIGHBORHOOD_IMP_H_
+#error You should not include this header directly
+#endif
+/*
+ * Private API (here for inline)
+ */
+static inline int
+_PyArrayNeighborhoodIter_IncrCoord(PyArrayNeighborhoodIterObject* iter);
+
+/*
+ * Update to next item of the iterator
+ *
+ * Note: this simply increment the coordinates vector, last dimension
+ * incremented first , i.e, for dimension 3
+ * ...
+ * -1, -1, -1
+ * -1, -1, 0
+ * -1, -1, 1
+ * ....
+ * -1, 0, -1
+ * -1, 0, 0
+ * ....
+ * 0, -1, -1
+ * 0, -1, 0
+ * ....
+ */
+#define _UPDATE_COORD_ITER(c) \
+ wb = iter->coordinates[c] < iter->bounds[c][1]; \
+ if (wb) { \
+ iter->coordinates[c] += 1; \
+ return 0; \
+ } \
+ else { \
+ iter->coordinates[c] = iter->bounds[c][0]; \
+ }
+
+static inline int
+_PyArrayNeighborhoodIter_IncrCoord(PyArrayNeighborhoodIterObject* iter)
+{
+ npy_intp i, wb;
+
+ for (i = iter->nd - 1; i >= 0; --i) {
+ _UPDATE_COORD_ITER(i)
+ }
+
+ return 0;
+}
+
+/*
+ * Version optimized for 2d arrays, manual loop unrolling
+ */
+static inline int
+_PyArrayNeighborhoodIter_IncrCoord2D(PyArrayNeighborhoodIterObject* iter)
+{
+ npy_intp wb;
+
+ _UPDATE_COORD_ITER(1)
+ _UPDATE_COORD_ITER(0)
+
+ return 0;
+}
+#undef _UPDATE_COORD_ITER
+
+/*
+ * Advance to the next neighbour
+ */
+static inline int
+PyArrayNeighborhoodIter_Next(PyArrayNeighborhoodIterObject* iter)
+{
+ _PyArrayNeighborhoodIter_IncrCoord (iter);
+ iter->dataptr = iter->translate((PyArrayIterObject*)iter, iter->coordinates);
+
+ return 0;
+}
+
+/*
+ * Reset functions
+ */
+static inline int
+PyArrayNeighborhoodIter_Reset(PyArrayNeighborhoodIterObject* iter)
+{
+ npy_intp i;
+
+ for (i = 0; i < iter->nd; ++i) {
+ iter->coordinates[i] = iter->bounds[i][0];
+ }
+ iter->dataptr = iter->translate((PyArrayIterObject*)iter, iter->coordinates);
+
+ return 0;
+}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/_numpyconfig.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/_numpyconfig.h
new file mode 100644
index 0000000000000000000000000000000000000000..6e50e16505bbc9ad5f859ff63dd16978c7cd3ecb
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/_numpyconfig.h
@@ -0,0 +1,33 @@
+#define NPY_HAVE_ENDIAN_H 1
+
+#define NPY_SIZEOF_SHORT 2
+#define NPY_SIZEOF_INT 4
+#define NPY_SIZEOF_LONG 8
+#define NPY_SIZEOF_FLOAT 4
+#define NPY_SIZEOF_COMPLEX_FLOAT 8
+#define NPY_SIZEOF_DOUBLE 8
+#define NPY_SIZEOF_COMPLEX_DOUBLE 16
+#define NPY_SIZEOF_LONGDOUBLE 16
+#define NPY_SIZEOF_COMPLEX_LONGDOUBLE 32
+#define NPY_SIZEOF_PY_INTPTR_T 8
+#define NPY_SIZEOF_INTP 8
+#define NPY_SIZEOF_UINTP 8
+#define NPY_SIZEOF_WCHAR_T 4
+#define NPY_SIZEOF_OFF_T 8
+#define NPY_SIZEOF_PY_LONG_LONG 8
+#define NPY_SIZEOF_LONGLONG 8
+
+/*
+ * Defined to 1 or 0. Note that Pyodide hardcodes NPY_NO_SMP (and other defines
+ * in this header) for better cross-compilation, so don't rename them without a
+ * good reason.
+ */
+#define NPY_NO_SMP 0
+
+#define NPY_VISIBILITY_HIDDEN __attribute__((visibility("hidden")))
+#define NPY_ABI_VERSION 0x02000000
+#define NPY_API_VERSION 0x00000013
+
+#ifndef __STDC_FORMAT_MACROS
+#define __STDC_FORMAT_MACROS 1
+#endif
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/_public_dtype_api_table.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/_public_dtype_api_table.h
new file mode 100644
index 0000000000000000000000000000000000000000..51f39054062762c39b3df4f689b74060e97036c0
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/_public_dtype_api_table.h
@@ -0,0 +1,86 @@
+/*
+ * Public exposure of the DType Classes. These are tricky to expose
+ * via the Python API, so they are exposed through this header for now.
+ *
+ * These definitions are only relevant for the public API and we reserve
+ * the slots 320-360 in the API table generation for this (currently).
+ *
+ * TODO: This file should be consolidated with the API table generation
+ * (although not sure the current generation is worth preserving).
+ */
+#ifndef NUMPY_CORE_INCLUDE_NUMPY__PUBLIC_DTYPE_API_TABLE_H_
+#define NUMPY_CORE_INCLUDE_NUMPY__PUBLIC_DTYPE_API_TABLE_H_
+
+#if !(defined(NPY_INTERNAL_BUILD) && NPY_INTERNAL_BUILD)
+
+/* All of these require NumPy 2.0 support */
+#if NPY_FEATURE_VERSION >= NPY_2_0_API_VERSION
+
+/*
+ * The type of the DType metaclass
+ */
+#define PyArrayDTypeMeta_Type (*(PyTypeObject *)(PyArray_API + 320)[0])
+/*
+ * NumPy's builtin DTypes:
+ */
+#define PyArray_BoolDType (*(PyArray_DTypeMeta *)(PyArray_API + 320)[1])
+/* Integers */
+#define PyArray_ByteDType (*(PyArray_DTypeMeta *)(PyArray_API + 320)[2])
+#define PyArray_UByteDType (*(PyArray_DTypeMeta *)(PyArray_API + 320)[3])
+#define PyArray_ShortDType (*(PyArray_DTypeMeta *)(PyArray_API + 320)[4])
+#define PyArray_UShortDType (*(PyArray_DTypeMeta *)(PyArray_API + 320)[5])
+#define PyArray_IntDType (*(PyArray_DTypeMeta *)(PyArray_API + 320)[6])
+#define PyArray_UIntDType (*(PyArray_DTypeMeta *)(PyArray_API + 320)[7])
+#define PyArray_LongDType (*(PyArray_DTypeMeta *)(PyArray_API + 320)[8])
+#define PyArray_ULongDType (*(PyArray_DTypeMeta *)(PyArray_API + 320)[9])
+#define PyArray_LongLongDType (*(PyArray_DTypeMeta *)(PyArray_API + 320)[10])
+#define PyArray_ULongLongDType (*(PyArray_DTypeMeta *)(PyArray_API + 320)[11])
+/* Integer aliases */
+#define PyArray_Int8DType (*(PyArray_DTypeMeta *)(PyArray_API + 320)[12])
+#define PyArray_UInt8DType (*(PyArray_DTypeMeta *)(PyArray_API + 320)[13])
+#define PyArray_Int16DType (*(PyArray_DTypeMeta *)(PyArray_API + 320)[14])
+#define PyArray_UInt16DType (*(PyArray_DTypeMeta *)(PyArray_API + 320)[15])
+#define PyArray_Int32DType (*(PyArray_DTypeMeta *)(PyArray_API + 320)[16])
+#define PyArray_UInt32DType (*(PyArray_DTypeMeta *)(PyArray_API + 320)[17])
+#define PyArray_Int64DType (*(PyArray_DTypeMeta *)(PyArray_API + 320)[18])
+#define PyArray_UInt64DType (*(PyArray_DTypeMeta *)(PyArray_API + 320)[19])
+#define PyArray_IntpDType (*(PyArray_DTypeMeta *)(PyArray_API + 320)[20])
+#define PyArray_UIntpDType (*(PyArray_DTypeMeta *)(PyArray_API + 320)[21])
+/* Floats */
+#define PyArray_HalfDType (*(PyArray_DTypeMeta *)(PyArray_API + 320)[22])
+#define PyArray_FloatDType (*(PyArray_DTypeMeta *)(PyArray_API + 320)[23])
+#define PyArray_DoubleDType (*(PyArray_DTypeMeta *)(PyArray_API + 320)[24])
+#define PyArray_LongDoubleDType (*(PyArray_DTypeMeta *)(PyArray_API + 320)[25])
+/* Complex */
+#define PyArray_CFloatDType (*(PyArray_DTypeMeta *)(PyArray_API + 320)[26])
+#define PyArray_CDoubleDType (*(PyArray_DTypeMeta *)(PyArray_API + 320)[27])
+#define PyArray_CLongDoubleDType (*(PyArray_DTypeMeta *)(PyArray_API + 320)[28])
+/* String/Bytes */
+#define PyArray_BytesDType (*(PyArray_DTypeMeta *)(PyArray_API + 320)[29])
+#define PyArray_UnicodeDType (*(PyArray_DTypeMeta *)(PyArray_API + 320)[30])
+/* Datetime/Timedelta */
+#define PyArray_DatetimeDType (*(PyArray_DTypeMeta *)(PyArray_API + 320)[31])
+#define PyArray_TimedeltaDType (*(PyArray_DTypeMeta *)(PyArray_API + 320)[32])
+/* Object/Void */
+#define PyArray_ObjectDType (*(PyArray_DTypeMeta *)(PyArray_API + 320)[33])
+#define PyArray_VoidDType (*(PyArray_DTypeMeta *)(PyArray_API + 320)[34])
+/* Python types (used as markers for scalars) */
+#define PyArray_PyLongDType (*(PyArray_DTypeMeta *)(PyArray_API + 320)[35])
+#define PyArray_PyFloatDType (*(PyArray_DTypeMeta *)(PyArray_API + 320)[36])
+#define PyArray_PyComplexDType (*(PyArray_DTypeMeta *)(PyArray_API + 320)[37])
+/* Default integer type */
+#define PyArray_DefaultIntDType (*(PyArray_DTypeMeta *)(PyArray_API + 320)[38])
+/* New non-legacy DTypes follow in the order they were added */
+#define PyArray_StringDType (*(PyArray_DTypeMeta *)(PyArray_API + 320)[39])
+
+/* NOTE: offset 40 is free */
+
+/* Need to start with a larger offset again for the abstract classes: */
+#define PyArray_IntAbstractDType (*(PyArray_DTypeMeta *)PyArray_API[366])
+#define PyArray_FloatAbstractDType (*(PyArray_DTypeMeta *)PyArray_API[367])
+#define PyArray_ComplexAbstractDType (*(PyArray_DTypeMeta *)PyArray_API[368])
+
+#endif /* NPY_FEATURE_VERSION >= NPY_2_0_API_VERSION */
+
+#endif /* NPY_INTERNAL_BUILD */
+#endif /* NUMPY_CORE_INCLUDE_NUMPY__PUBLIC_DTYPE_API_TABLE_H_ */
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/arrayobject.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/arrayobject.h
new file mode 100644
index 0000000000000000000000000000000000000000..97d93590e401fc878b72281d938170623f01da97
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/arrayobject.h
@@ -0,0 +1,7 @@
+#ifndef NUMPY_CORE_INCLUDE_NUMPY_ARRAYOBJECT_H_
+#define NUMPY_CORE_INCLUDE_NUMPY_ARRAYOBJECT_H_
+#define Py_ARRAYOBJECT_H
+
+#include "ndarrayobject.h"
+
+#endif /* NUMPY_CORE_INCLUDE_NUMPY_ARRAYOBJECT_H_ */
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/arrayscalars.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/arrayscalars.h
new file mode 100644
index 0000000000000000000000000000000000000000..ff048061f70abda097606b6247e32234d4eacf29
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/arrayscalars.h
@@ -0,0 +1,196 @@
+#ifndef NUMPY_CORE_INCLUDE_NUMPY_ARRAYSCALARS_H_
+#define NUMPY_CORE_INCLUDE_NUMPY_ARRAYSCALARS_H_
+
+#ifndef _MULTIARRAYMODULE
+typedef struct {
+ PyObject_HEAD
+ npy_bool obval;
+} PyBoolScalarObject;
+#endif
+
+
+typedef struct {
+ PyObject_HEAD
+ signed char obval;
+} PyByteScalarObject;
+
+
+typedef struct {
+ PyObject_HEAD
+ short obval;
+} PyShortScalarObject;
+
+
+typedef struct {
+ PyObject_HEAD
+ int obval;
+} PyIntScalarObject;
+
+
+typedef struct {
+ PyObject_HEAD
+ long obval;
+} PyLongScalarObject;
+
+
+typedef struct {
+ PyObject_HEAD
+ npy_longlong obval;
+} PyLongLongScalarObject;
+
+
+typedef struct {
+ PyObject_HEAD
+ unsigned char obval;
+} PyUByteScalarObject;
+
+
+typedef struct {
+ PyObject_HEAD
+ unsigned short obval;
+} PyUShortScalarObject;
+
+
+typedef struct {
+ PyObject_HEAD
+ unsigned int obval;
+} PyUIntScalarObject;
+
+
+typedef struct {
+ PyObject_HEAD
+ unsigned long obval;
+} PyULongScalarObject;
+
+
+typedef struct {
+ PyObject_HEAD
+ npy_ulonglong obval;
+} PyULongLongScalarObject;
+
+
+typedef struct {
+ PyObject_HEAD
+ npy_half obval;
+} PyHalfScalarObject;
+
+
+typedef struct {
+ PyObject_HEAD
+ float obval;
+} PyFloatScalarObject;
+
+
+typedef struct {
+ PyObject_HEAD
+ double obval;
+} PyDoubleScalarObject;
+
+
+typedef struct {
+ PyObject_HEAD
+ npy_longdouble obval;
+} PyLongDoubleScalarObject;
+
+
+typedef struct {
+ PyObject_HEAD
+ npy_cfloat obval;
+} PyCFloatScalarObject;
+
+
+typedef struct {
+ PyObject_HEAD
+ npy_cdouble obval;
+} PyCDoubleScalarObject;
+
+
+typedef struct {
+ PyObject_HEAD
+ npy_clongdouble obval;
+} PyCLongDoubleScalarObject;
+
+
+typedef struct {
+ PyObject_HEAD
+ PyObject * obval;
+} PyObjectScalarObject;
+
+typedef struct {
+ PyObject_HEAD
+ npy_datetime obval;
+ PyArray_DatetimeMetaData obmeta;
+} PyDatetimeScalarObject;
+
+typedef struct {
+ PyObject_HEAD
+ npy_timedelta obval;
+ PyArray_DatetimeMetaData obmeta;
+} PyTimedeltaScalarObject;
+
+
+typedef struct {
+ PyObject_HEAD
+ char obval;
+} PyScalarObject;
+
+#define PyStringScalarObject PyBytesObject
+#ifndef Py_LIMITED_API
+typedef struct {
+ /* note that the PyObject_HEAD macro lives right here */
+ PyUnicodeObject base;
+ Py_UCS4 *obval;
+ #if NPY_FEATURE_VERSION >= NPY_1_20_API_VERSION
+ char *buffer_fmt;
+ #endif
+} PyUnicodeScalarObject;
+#endif
+
+
+typedef struct {
+ PyObject_VAR_HEAD
+ char *obval;
+#if defined(NPY_INTERNAL_BUILD) && NPY_INTERNAL_BUILD
+ /* Internally use the subclass to allow accessing names/fields */
+ _PyArray_LegacyDescr *descr;
+#else
+ PyArray_Descr *descr;
+#endif
+ int flags;
+ PyObject *base;
+ #if NPY_FEATURE_VERSION >= NPY_1_20_API_VERSION
+ void *_buffer_info; /* private buffer info, tagged to allow warning */
+ #endif
+} PyVoidScalarObject;
+
+/* Macros
+ PyScalarObject
+ PyArrType_Type
+ are defined in ndarrayobject.h
+*/
+
+#define PyArrayScalar_False ((PyObject *)(&(_PyArrayScalar_BoolValues[0])))
+#define PyArrayScalar_True ((PyObject *)(&(_PyArrayScalar_BoolValues[1])))
+#define PyArrayScalar_FromLong(i) \
+ ((PyObject *)(&(_PyArrayScalar_BoolValues[((i)!=0)])))
+#define PyArrayScalar_RETURN_BOOL_FROM_LONG(i) \
+ return Py_INCREF(PyArrayScalar_FromLong(i)), \
+ PyArrayScalar_FromLong(i)
+#define PyArrayScalar_RETURN_FALSE \
+ return Py_INCREF(PyArrayScalar_False), \
+ PyArrayScalar_False
+#define PyArrayScalar_RETURN_TRUE \
+ return Py_INCREF(PyArrayScalar_True), \
+ PyArrayScalar_True
+
+#define PyArrayScalar_New(cls) \
+ Py##cls##ArrType_Type.tp_alloc(&Py##cls##ArrType_Type, 0)
+#ifndef Py_LIMITED_API
+/* For the limited API, use PyArray_ScalarAsCtype instead */
+#define PyArrayScalar_VAL(obj, cls) \
+ ((Py##cls##ScalarObject *)obj)->obval
+#define PyArrayScalar_ASSIGN(obj, cls, val) \
+ PyArrayScalar_VAL(obj, cls) = val
+#endif
+
+#endif /* NUMPY_CORE_INCLUDE_NUMPY_ARRAYSCALARS_H_ */
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/dtype_api.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/dtype_api.h
new file mode 100644
index 0000000000000000000000000000000000000000..b37c9fbb68213e8ff7817093bc4c1f495d84b79d
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/dtype_api.h
@@ -0,0 +1,480 @@
+/*
+ * The public DType API
+ */
+
+#ifndef NUMPY_CORE_INCLUDE_NUMPY___DTYPE_API_H_
+#define NUMPY_CORE_INCLUDE_NUMPY___DTYPE_API_H_
+
+struct PyArrayMethodObject_tag;
+
+/*
+ * Largely opaque struct for DType classes (i.e. metaclass instances).
+ * The internal definition is currently in `ndarraytypes.h` (export is a bit
+ * more complex because `PyArray_Descr` is a DTypeMeta internally but not
+ * externally).
+ */
+#if !(defined(NPY_INTERNAL_BUILD) && NPY_INTERNAL_BUILD)
+
+#ifndef Py_LIMITED_API
+
+ typedef struct PyArray_DTypeMeta_tag {
+ PyHeapTypeObject super;
+
+ /*
+ * Most DTypes will have a singleton default instance, for the
+ * parametric legacy DTypes (bytes, string, void, datetime) this
+ * may be a pointer to the *prototype* instance?
+ */
+ PyArray_Descr *singleton;
+ /* Copy of the legacy DTypes type number, usually invalid. */
+ int type_num;
+
+ /* The type object of the scalar instances (may be NULL?) */
+ PyTypeObject *scalar_type;
+ /*
+ * DType flags to signal legacy, parametric, or
+ * abstract. But plenty of space for additional information/flags.
+ */
+ npy_uint64 flags;
+
+ /*
+ * Use indirection in order to allow a fixed size for this struct.
+ * A stable ABI size makes creating a static DType less painful
+ * while also ensuring flexibility for all opaque API (with one
+ * indirection due the pointer lookup).
+ */
+ void *dt_slots;
+ /* Allow growing (at the moment also beyond this) */
+ void *reserved[3];
+ } PyArray_DTypeMeta;
+
+#else
+
+typedef PyTypeObject PyArray_DTypeMeta;
+
+#endif /* Py_LIMITED_API */
+
+#endif /* not internal build */
+
+/*
+ * ******************************************************
+ * ArrayMethod API (Casting and UFuncs)
+ * ******************************************************
+ */
+
+
+typedef enum {
+ /* Flag for whether the GIL is required */
+ NPY_METH_REQUIRES_PYAPI = 1 << 0,
+ /*
+ * Some functions cannot set floating point error flags, this flag
+ * gives us the option (not requirement) to skip floating point error
+ * setup/check. No function should set error flags and ignore them
+ * since it would interfere with chaining operations (e.g. casting).
+ */
+ NPY_METH_NO_FLOATINGPOINT_ERRORS = 1 << 1,
+ /* Whether the method supports unaligned access (not runtime) */
+ NPY_METH_SUPPORTS_UNALIGNED = 1 << 2,
+ /*
+ * Used for reductions to allow reordering the operation. At this point
+ * assume that if set, it also applies to normal operations though!
+ */
+ NPY_METH_IS_REORDERABLE = 1 << 3,
+ /*
+ * Private flag for now for *logic* functions. The logical functions
+ * `logical_or` and `logical_and` can always cast the inputs to booleans
+ * "safely" (because that is how the cast to bool is defined).
+ * @seberg: I am not sure this is the best way to handle this, so its
+ * private for now (also it is very limited anyway).
+ * There is one "exception". NA aware dtypes cannot cast to bool
+ * (hopefully), so the `??->?` loop should error even with this flag.
+ * But a second NA fallback loop will be necessary.
+ */
+ _NPY_METH_FORCE_CAST_INPUTS = 1 << 17,
+
+ /* All flags which can change at runtime */
+ NPY_METH_RUNTIME_FLAGS = (
+ NPY_METH_REQUIRES_PYAPI |
+ NPY_METH_NO_FLOATINGPOINT_ERRORS),
+} NPY_ARRAYMETHOD_FLAGS;
+
+
+typedef struct PyArrayMethod_Context_tag {
+ /* The caller, which is typically the original ufunc. May be NULL */
+ PyObject *caller;
+ /* The method "self". Currently an opaque object. */
+ struct PyArrayMethodObject_tag *method;
+
+ /* Operand descriptors, filled in by resolve_descriptors */
+ PyArray_Descr *const *descriptors;
+ /* Structure may grow (this is harmless for DType authors) */
+} PyArrayMethod_Context;
+
+
+/*
+ * The main object for creating a new ArrayMethod. We use the typical `slots`
+ * mechanism used by the Python limited API (see below for the slot defs).
+ */
+typedef struct {
+ const char *name;
+ int nin, nout;
+ NPY_CASTING casting;
+ NPY_ARRAYMETHOD_FLAGS flags;
+ PyArray_DTypeMeta **dtypes;
+ PyType_Slot *slots;
+} PyArrayMethod_Spec;
+
+
+/*
+ * ArrayMethod slots
+ * -----------------
+ *
+ * SLOTS IDs For the ArrayMethod creation, once fully public, IDs are fixed
+ * but can be deprecated and arbitrarily extended.
+ */
+#define _NPY_METH_resolve_descriptors_with_scalars 1
+#define NPY_METH_resolve_descriptors 2
+#define NPY_METH_get_loop 3
+#define NPY_METH_get_reduction_initial 4
+/* specific loops for constructions/default get_loop: */
+#define NPY_METH_strided_loop 5
+#define NPY_METH_contiguous_loop 6
+#define NPY_METH_unaligned_strided_loop 7
+#define NPY_METH_unaligned_contiguous_loop 8
+#define NPY_METH_contiguous_indexed_loop 9
+#define _NPY_METH_static_data 10
+
+
+/*
+ * The resolve descriptors function, must be able to handle NULL values for
+ * all output (but not input) `given_descrs` and fill `loop_descrs`.
+ * Return -1 on error or 0 if the operation is not possible without an error
+ * set. (This may still be in flux.)
+ * Otherwise must return the "casting safety", for normal functions, this is
+ * almost always "safe" (or even "equivalent"?).
+ *
+ * `resolve_descriptors` is optional if all output DTypes are non-parametric.
+ */
+typedef NPY_CASTING (PyArrayMethod_ResolveDescriptors)(
+ /* "method" is currently opaque (necessary e.g. to wrap Python) */
+ struct PyArrayMethodObject_tag *method,
+ /* DTypes the method was created for */
+ PyArray_DTypeMeta *const *dtypes,
+ /* Input descriptors (instances). Outputs may be NULL. */
+ PyArray_Descr *const *given_descrs,
+ /* Exact loop descriptors to use, must not hold references on error */
+ PyArray_Descr **loop_descrs,
+ npy_intp *view_offset);
+
+
+/*
+ * Rarely needed, slightly more powerful version of `resolve_descriptors`.
+ * See also `PyArrayMethod_ResolveDescriptors` for details on shared arguments.
+ *
+ * NOTE: This function is private now as it is unclear how and what to pass
+ * exactly as additional information to allow dealing with the scalars.
+ * See also gh-24915.
+ */
+typedef NPY_CASTING (PyArrayMethod_ResolveDescriptorsWithScalar)(
+ struct PyArrayMethodObject_tag *method,
+ PyArray_DTypeMeta *const *dtypes,
+ /* Unlike above, these can have any DType and we may allow NULL. */
+ PyArray_Descr *const *given_descrs,
+ /*
+ * Input scalars or NULL. Only ever passed for python scalars.
+ * WARNING: In some cases, a loop may be explicitly selected and the
+ * value passed is not available (NULL) or does not have the
+ * expected type.
+ */
+ PyObject *const *input_scalars,
+ PyArray_Descr **loop_descrs,
+ npy_intp *view_offset);
+
+
+
+typedef int (PyArrayMethod_StridedLoop)(PyArrayMethod_Context *context,
+ char *const *data, const npy_intp *dimensions, const npy_intp *strides,
+ NpyAuxData *transferdata);
+
+
+typedef int (PyArrayMethod_GetLoop)(
+ PyArrayMethod_Context *context,
+ int aligned, int move_references,
+ const npy_intp *strides,
+ PyArrayMethod_StridedLoop **out_loop,
+ NpyAuxData **out_transferdata,
+ NPY_ARRAYMETHOD_FLAGS *flags);
+
+/**
+ * Query an ArrayMethod for the initial value for use in reduction.
+ *
+ * @param context The arraymethod context, mainly to access the descriptors.
+ * @param reduction_is_empty Whether the reduction is empty. When it is, the
+ * value returned may differ. In this case it is a "default" value that
+ * may differ from the "identity" value normally used. For example:
+ * - `0.0` is the default for `sum([])`. But `-0.0` is the correct
+ * identity otherwise as it preserves the sign for `sum([-0.0])`.
+ * - We use no identity for object, but return the default of `0` and `1`
+ * for the empty `sum([], dtype=object)` and `prod([], dtype=object)`.
+ * This allows `np.sum(np.array(["a", "b"], dtype=object))` to work.
+ * - `-inf` or `INT_MIN` for `max` is an identity, but at least `INT_MIN`
+ * not a good *default* when there are no items.
+ * @param initial Pointer to initial data to be filled (if possible)
+ *
+ * @returns -1, 0, or 1 indicating error, no initial value, and initial being
+ * successfully filled. Errors must not be given where 0 is correct, NumPy
+ * may call this even when not strictly necessary.
+ */
+typedef int (PyArrayMethod_GetReductionInitial)(
+ PyArrayMethod_Context *context, npy_bool reduction_is_empty,
+ void *initial);
+
+/*
+ * The following functions are only used by the wrapping array method defined
+ * in umath/wrapping_array_method.c
+ */
+
+
+/*
+ * The function to convert the given descriptors (passed in to
+ * `resolve_descriptors`) and translates them for the wrapped loop.
+ * The new descriptors MUST be viewable with the old ones, `NULL` must be
+ * supported (for outputs) and should normally be forwarded.
+ *
+ * The function must clean up on error.
+ *
+ * NOTE: We currently assume that this translation gives "viewable" results.
+ * I.e. there is no additional casting related to the wrapping process.
+ * In principle that could be supported, but not sure it is useful.
+ * This currently also means that e.g. alignment must apply identically
+ * to the new dtypes.
+ *
+ * TODO: Due to the fact that `resolve_descriptors` is also used for `can_cast`
+ * there is no way to "pass out" the result of this function. This means
+ * it will be called twice for every ufunc call.
+ * (I am considering including `auxdata` as an "optional" parameter to
+ * `resolve_descriptors`, so that it can be filled there if not NULL.)
+ */
+typedef int (PyArrayMethod_TranslateGivenDescriptors)(int nin, int nout,
+ PyArray_DTypeMeta *const wrapped_dtypes[],
+ PyArray_Descr *const given_descrs[], PyArray_Descr *new_descrs[]);
+
+/**
+ * The function to convert the actual loop descriptors (as returned by the
+ * original `resolve_descriptors` function) to the ones the output array
+ * should use.
+ * This function must return "viewable" types, it must not mutate them in any
+ * form that would break the inner-loop logic. Does not need to support NULL.
+ *
+ * The function must clean up on error.
+ *
+ * @param nin Number of input arguments
+ * @param nout Number of output arguments
+ * @param new_dtypes The DTypes of the output (usually probably not needed)
+ * @param given_descrs Original given_descrs to the resolver, necessary to
+ * fetch any information related to the new dtypes from the original.
+ * @param original_descrs The `loop_descrs` returned by the wrapped loop.
+ * @param loop_descrs The output descriptors, compatible to `original_descrs`.
+ *
+ * @returns 0 on success, -1 on failure.
+ */
+typedef int (PyArrayMethod_TranslateLoopDescriptors)(int nin, int nout,
+ PyArray_DTypeMeta *const new_dtypes[], PyArray_Descr *const given_descrs[],
+ PyArray_Descr *original_descrs[], PyArray_Descr *loop_descrs[]);
+
+
+
+/*
+ * A traverse loop working on a single array. This is similar to the general
+ * strided-loop function. This is designed for loops that need to visit every
+ * element of a single array.
+ *
+ * Currently this is used for array clearing, via the NPY_DT_get_clear_loop
+ * API hook, and zero-filling, via the NPY_DT_get_fill_zero_loop API hook.
+ * These are most useful for handling arrays storing embedded references to
+ * python objects or heap-allocated data.
+ *
+ * The `void *traverse_context` is passed in because we may need to pass in
+ * Interpreter state or similar in the future, but we don't want to pass in
+ * a full context (with pointers to dtypes, method, caller which all make
+ * no sense for a traverse function).
+ *
+ * We assume for now that this context can be just passed through in the
+ * the future (for structured dtypes).
+ *
+ */
+typedef int (PyArrayMethod_TraverseLoop)(
+ void *traverse_context, const PyArray_Descr *descr, char *data,
+ npy_intp size, npy_intp stride, NpyAuxData *auxdata);
+
+
+/*
+ * Simplified get_loop function specific to dtype traversal
+ *
+ * It should set the flags needed for the traversal loop and set out_loop to the
+ * loop function, which must be a valid PyArrayMethod_TraverseLoop
+ * pointer. Currently this is used for zero-filling and clearing arrays storing
+ * embedded references.
+ *
+ */
+typedef int (PyArrayMethod_GetTraverseLoop)(
+ void *traverse_context, const PyArray_Descr *descr,
+ int aligned, npy_intp fixed_stride,
+ PyArrayMethod_TraverseLoop **out_loop, NpyAuxData **out_auxdata,
+ NPY_ARRAYMETHOD_FLAGS *flags);
+
+
+/*
+ * Type of the C promoter function, which must be wrapped into a
+ * PyCapsule with name "numpy._ufunc_promoter".
+ *
+ * Note that currently the output dtypes are always NULL unless they are
+ * also part of the signature. This is an implementation detail and could
+ * change in the future. However, in general promoters should not have a
+ * need for output dtypes.
+ * (There are potential use-cases, these are currently unsupported.)
+ */
+typedef int (PyArrayMethod_PromoterFunction)(PyObject *ufunc,
+ PyArray_DTypeMeta *const op_dtypes[], PyArray_DTypeMeta *const signature[],
+ PyArray_DTypeMeta *new_op_dtypes[]);
+
+/*
+ * ****************************
+ * DTYPE API
+ * ****************************
+ */
+
+#define NPY_DT_ABSTRACT 1 << 1
+#define NPY_DT_PARAMETRIC 1 << 2
+#define NPY_DT_NUMERIC 1 << 3
+
+/*
+ * These correspond to slots in the NPY_DType_Slots struct and must
+ * be in the same order as the members of that struct. If new slots
+ * get added or old slots get removed NPY_NUM_DTYPE_SLOTS must also
+ * be updated
+ */
+
+#define NPY_DT_discover_descr_from_pyobject 1
+// this slot is considered private because its API hasn't been decided
+#define _NPY_DT_is_known_scalar_type 2
+#define NPY_DT_default_descr 3
+#define NPY_DT_common_dtype 4
+#define NPY_DT_common_instance 5
+#define NPY_DT_ensure_canonical 6
+#define NPY_DT_setitem 7
+#define NPY_DT_getitem 8
+#define NPY_DT_get_clear_loop 9
+#define NPY_DT_get_fill_zero_loop 10
+#define NPY_DT_finalize_descr 11
+
+// These PyArray_ArrFunc slots will be deprecated and replaced eventually
+// getitem and setitem can be defined as a performance optimization;
+// by default the user dtypes call `legacy_getitem_using_DType` and
+// `legacy_setitem_using_DType`, respectively. This functionality is
+// only supported for basic NumPy DTypes.
+
+
+// used to separate dtype slots from arrfuncs slots
+// intended only for internal use but defined here for clarity
+#define _NPY_DT_ARRFUNCS_OFFSET (1 << 10)
+
+// Cast is disabled
+// #define NPY_DT_PyArray_ArrFuncs_cast 0 + _NPY_DT_ARRFUNCS_OFFSET
+
+#define NPY_DT_PyArray_ArrFuncs_getitem 1 + _NPY_DT_ARRFUNCS_OFFSET
+#define NPY_DT_PyArray_ArrFuncs_setitem 2 + _NPY_DT_ARRFUNCS_OFFSET
+
+// Copyswap is disabled
+// #define NPY_DT_PyArray_ArrFuncs_copyswapn 3 + _NPY_DT_ARRFUNCS_OFFSET
+// #define NPY_DT_PyArray_ArrFuncs_copyswap 4 + _NPY_DT_ARRFUNCS_OFFSET
+#define NPY_DT_PyArray_ArrFuncs_compare 5 + _NPY_DT_ARRFUNCS_OFFSET
+#define NPY_DT_PyArray_ArrFuncs_argmax 6 + _NPY_DT_ARRFUNCS_OFFSET
+#define NPY_DT_PyArray_ArrFuncs_dotfunc 7 + _NPY_DT_ARRFUNCS_OFFSET
+#define NPY_DT_PyArray_ArrFuncs_scanfunc 8 + _NPY_DT_ARRFUNCS_OFFSET
+#define NPY_DT_PyArray_ArrFuncs_fromstr 9 + _NPY_DT_ARRFUNCS_OFFSET
+#define NPY_DT_PyArray_ArrFuncs_nonzero 10 + _NPY_DT_ARRFUNCS_OFFSET
+#define NPY_DT_PyArray_ArrFuncs_fill 11 + _NPY_DT_ARRFUNCS_OFFSET
+#define NPY_DT_PyArray_ArrFuncs_fillwithscalar 12 + _NPY_DT_ARRFUNCS_OFFSET
+#define NPY_DT_PyArray_ArrFuncs_sort 13 + _NPY_DT_ARRFUNCS_OFFSET
+#define NPY_DT_PyArray_ArrFuncs_argsort 14 + _NPY_DT_ARRFUNCS_OFFSET
+
+// Casting related slots are disabled. See
+// https://github.com/numpy/numpy/pull/23173#discussion_r1101098163
+// #define NPY_DT_PyArray_ArrFuncs_castdict 15 + _NPY_DT_ARRFUNCS_OFFSET
+// #define NPY_DT_PyArray_ArrFuncs_scalarkind 16 + _NPY_DT_ARRFUNCS_OFFSET
+// #define NPY_DT_PyArray_ArrFuncs_cancastscalarkindto 17 + _NPY_DT_ARRFUNCS_OFFSET
+// #define NPY_DT_PyArray_ArrFuncs_cancastto 18 + _NPY_DT_ARRFUNCS_OFFSET
+
+// These are deprecated in NumPy 1.19, so are disabled here.
+// #define NPY_DT_PyArray_ArrFuncs_fastclip 19 + _NPY_DT_ARRFUNCS_OFFSET
+// #define NPY_DT_PyArray_ArrFuncs_fastputmask 20 + _NPY_DT_ARRFUNCS_OFFSET
+// #define NPY_DT_PyArray_ArrFuncs_fasttake 21 + _NPY_DT_ARRFUNCS_OFFSET
+#define NPY_DT_PyArray_ArrFuncs_argmin 22 + _NPY_DT_ARRFUNCS_OFFSET
+
+
+// TODO: These slots probably still need some thought, and/or a way to "grow"?
+typedef struct {
+ PyTypeObject *typeobj; /* type of python scalar or NULL */
+ int flags; /* flags, including parametric and abstract */
+ /* NULL terminated cast definitions. Use NULL for the newly created DType */
+ PyArrayMethod_Spec **casts;
+ PyType_Slot *slots;
+ /* Baseclass or NULL (will always subclass `np.dtype`) */
+ PyTypeObject *baseclass;
+} PyArrayDTypeMeta_Spec;
+
+
+typedef PyArray_Descr *(PyArrayDTypeMeta_DiscoverDescrFromPyobject)(
+ PyArray_DTypeMeta *cls, PyObject *obj);
+
+/*
+ * Before making this public, we should decide whether it should pass
+ * the type, or allow looking at the object. A possible use-case:
+ * `np.array(np.array([0]), dtype=np.ndarray)`
+ * Could consider arrays that are not `dtype=ndarray` "scalars".
+ */
+typedef int (PyArrayDTypeMeta_IsKnownScalarType)(
+ PyArray_DTypeMeta *cls, PyTypeObject *obj);
+
+typedef PyArray_Descr *(PyArrayDTypeMeta_DefaultDescriptor)(PyArray_DTypeMeta *cls);
+typedef PyArray_DTypeMeta *(PyArrayDTypeMeta_CommonDType)(
+ PyArray_DTypeMeta *dtype1, PyArray_DTypeMeta *dtype2);
+
+
+/*
+ * Convenience utility for getting a reference to the DType metaclass associated
+ * with a dtype instance.
+ */
+#define NPY_DTYPE(descr) ((PyArray_DTypeMeta *)Py_TYPE(descr))
+
+static inline PyArray_DTypeMeta *
+NPY_DT_NewRef(PyArray_DTypeMeta *o) {
+ Py_INCREF((PyObject *)o);
+ return o;
+}
+
+
+typedef PyArray_Descr *(PyArrayDTypeMeta_CommonInstance)(
+ PyArray_Descr *dtype1, PyArray_Descr *dtype2);
+typedef PyArray_Descr *(PyArrayDTypeMeta_EnsureCanonical)(PyArray_Descr *dtype);
+/*
+ * Returns either a new reference to *dtype* or a new descriptor instance
+ * initialized with the same parameters as *dtype*. The caller cannot know
+ * which choice a dtype will make. This function is called just before the
+ * array buffer is created for a newly created array, it is not called for
+ * views and the descriptor returned by this function is attached to the array.
+ */
+typedef PyArray_Descr *(PyArrayDTypeMeta_FinalizeDescriptor)(PyArray_Descr *dtype);
+
+/*
+ * TODO: These two functions are currently only used for experimental DType
+ * API support. Their relation should be "reversed": NumPy should
+ * always use them internally.
+ * There are open points about "casting safety" though, e.g. setting
+ * elements is currently always unsafe.
+ */
+typedef int(PyArrayDTypeMeta_SetItem)(PyArray_Descr *, PyObject *, char *);
+typedef PyObject *(PyArrayDTypeMeta_GetItem)(PyArray_Descr *, char *);
+
+#endif /* NUMPY_CORE_INCLUDE_NUMPY___DTYPE_API_H_ */
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/halffloat.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/halffloat.h
new file mode 100644
index 0000000000000000000000000000000000000000..950401664e101d17ce5461ecb21c7d3bdf824f42
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/halffloat.h
@@ -0,0 +1,70 @@
+#ifndef NUMPY_CORE_INCLUDE_NUMPY_HALFFLOAT_H_
+#define NUMPY_CORE_INCLUDE_NUMPY_HALFFLOAT_H_
+
+#include
+#include
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * Half-precision routines
+ */
+
+/* Conversions */
+float npy_half_to_float(npy_half h);
+double npy_half_to_double(npy_half h);
+npy_half npy_float_to_half(float f);
+npy_half npy_double_to_half(double d);
+/* Comparisons */
+int npy_half_eq(npy_half h1, npy_half h2);
+int npy_half_ne(npy_half h1, npy_half h2);
+int npy_half_le(npy_half h1, npy_half h2);
+int npy_half_lt(npy_half h1, npy_half h2);
+int npy_half_ge(npy_half h1, npy_half h2);
+int npy_half_gt(npy_half h1, npy_half h2);
+/* faster *_nonan variants for when you know h1 and h2 are not NaN */
+int npy_half_eq_nonan(npy_half h1, npy_half h2);
+int npy_half_lt_nonan(npy_half h1, npy_half h2);
+int npy_half_le_nonan(npy_half h1, npy_half h2);
+/* Miscellaneous functions */
+int npy_half_iszero(npy_half h);
+int npy_half_isnan(npy_half h);
+int npy_half_isinf(npy_half h);
+int npy_half_isfinite(npy_half h);
+int npy_half_signbit(npy_half h);
+npy_half npy_half_copysign(npy_half x, npy_half y);
+npy_half npy_half_spacing(npy_half h);
+npy_half npy_half_nextafter(npy_half x, npy_half y);
+npy_half npy_half_divmod(npy_half x, npy_half y, npy_half *modulus);
+
+/*
+ * Half-precision constants
+ */
+
+#define NPY_HALF_ZERO (0x0000u)
+#define NPY_HALF_PZERO (0x0000u)
+#define NPY_HALF_NZERO (0x8000u)
+#define NPY_HALF_ONE (0x3c00u)
+#define NPY_HALF_NEGONE (0xbc00u)
+#define NPY_HALF_PINF (0x7c00u)
+#define NPY_HALF_NINF (0xfc00u)
+#define NPY_HALF_NAN (0x7e00u)
+
+#define NPY_MAX_HALF (0x7bffu)
+
+/*
+ * Bit-level conversions
+ */
+
+npy_uint16 npy_floatbits_to_halfbits(npy_uint32 f);
+npy_uint16 npy_doublebits_to_halfbits(npy_uint64 d);
+npy_uint32 npy_halfbits_to_floatbits(npy_uint16 h);
+npy_uint64 npy_halfbits_to_doublebits(npy_uint16 h);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* NUMPY_CORE_INCLUDE_NUMPY_HALFFLOAT_H_ */
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/ndarrayobject.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/ndarrayobject.h
new file mode 100644
index 0000000000000000000000000000000000000000..f06bafe5b52a4ab930c2aad0c45d95d0b6d8104b
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/ndarrayobject.h
@@ -0,0 +1,304 @@
+/*
+ * DON'T INCLUDE THIS DIRECTLY.
+ */
+#ifndef NUMPY_CORE_INCLUDE_NUMPY_NDARRAYOBJECT_H_
+#define NUMPY_CORE_INCLUDE_NUMPY_NDARRAYOBJECT_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include
+#include "ndarraytypes.h"
+#include "dtype_api.h"
+
+/* Includes the "function" C-API -- these are all stored in a
+ list of pointers --- one for each file
+ The two lists are concatenated into one in multiarray.
+
+ They are available as import_array()
+*/
+
+#include "__multiarray_api.h"
+
+/*
+ * Include any definitions which are defined differently for 1.x and 2.x
+ * (Symbols only available on 2.x are not there, but rather guarded.)
+ */
+#include "npy_2_compat.h"
+
+/* C-API that requires previous API to be defined */
+
+#define PyArray_DescrCheck(op) PyObject_TypeCheck(op, &PyArrayDescr_Type)
+
+#define PyArray_Check(op) PyObject_TypeCheck(op, &PyArray_Type)
+#define PyArray_CheckExact(op) (((PyObject*)(op))->ob_type == &PyArray_Type)
+
+#define PyArray_HasArrayInterfaceType(op, type, context, out) \
+ ((((out)=PyArray_FromStructInterface(op)) != Py_NotImplemented) || \
+ (((out)=PyArray_FromInterface(op)) != Py_NotImplemented) || \
+ (((out)=PyArray_FromArrayAttr(op, type, context)) != \
+ Py_NotImplemented))
+
+#define PyArray_HasArrayInterface(op, out) \
+ PyArray_HasArrayInterfaceType(op, NULL, NULL, out)
+
+#define PyArray_IsZeroDim(op) (PyArray_Check(op) && \
+ (PyArray_NDIM((PyArrayObject *)op) == 0))
+
+#define PyArray_IsScalar(obj, cls) \
+ (PyObject_TypeCheck(obj, &Py##cls##ArrType_Type))
+
+#define PyArray_CheckScalar(m) (PyArray_IsScalar(m, Generic) || \
+ PyArray_IsZeroDim(m))
+#define PyArray_IsPythonNumber(obj) \
+ (PyFloat_Check(obj) || PyComplex_Check(obj) || \
+ PyLong_Check(obj) || PyBool_Check(obj))
+#define PyArray_IsIntegerScalar(obj) (PyLong_Check(obj) \
+ || PyArray_IsScalar((obj), Integer))
+#define PyArray_IsPythonScalar(obj) \
+ (PyArray_IsPythonNumber(obj) || PyBytes_Check(obj) || \
+ PyUnicode_Check(obj))
+
+#define PyArray_IsAnyScalar(obj) \
+ (PyArray_IsScalar(obj, Generic) || PyArray_IsPythonScalar(obj))
+
+#define PyArray_CheckAnyScalar(obj) (PyArray_IsPythonScalar(obj) || \
+ PyArray_CheckScalar(obj))
+
+
+#define PyArray_GETCONTIGUOUS(m) (PyArray_ISCONTIGUOUS(m) ? \
+ Py_INCREF(m), (m) : \
+ (PyArrayObject *)(PyArray_Copy(m)))
+
+#define PyArray_SAMESHAPE(a1,a2) ((PyArray_NDIM(a1) == PyArray_NDIM(a2)) && \
+ PyArray_CompareLists(PyArray_DIMS(a1), \
+ PyArray_DIMS(a2), \
+ PyArray_NDIM(a1)))
+
+#define PyArray_SIZE(m) PyArray_MultiplyList(PyArray_DIMS(m), PyArray_NDIM(m))
+#define PyArray_NBYTES(m) (PyArray_ITEMSIZE(m) * PyArray_SIZE(m))
+#define PyArray_FROM_O(m) PyArray_FromAny(m, NULL, 0, 0, 0, NULL)
+
+#define PyArray_FROM_OF(m,flags) PyArray_CheckFromAny(m, NULL, 0, 0, flags, \
+ NULL)
+
+#define PyArray_FROM_OT(m,type) PyArray_FromAny(m, \
+ PyArray_DescrFromType(type), 0, 0, 0, NULL)
+
+#define PyArray_FROM_OTF(m, type, flags) \
+ PyArray_FromAny(m, PyArray_DescrFromType(type), 0, 0, \
+ (((flags) & NPY_ARRAY_ENSURECOPY) ? \
+ ((flags) | NPY_ARRAY_DEFAULT) : (flags)), NULL)
+
+#define PyArray_FROMANY(m, type, min, max, flags) \
+ PyArray_FromAny(m, PyArray_DescrFromType(type), min, max, \
+ (((flags) & NPY_ARRAY_ENSURECOPY) ? \
+ (flags) | NPY_ARRAY_DEFAULT : (flags)), NULL)
+
+#define PyArray_ZEROS(m, dims, type, is_f_order) \
+ PyArray_Zeros(m, dims, PyArray_DescrFromType(type), is_f_order)
+
+#define PyArray_EMPTY(m, dims, type, is_f_order) \
+ PyArray_Empty(m, dims, PyArray_DescrFromType(type), is_f_order)
+
+#define PyArray_FILLWBYTE(obj, val) memset(PyArray_DATA(obj), val, \
+ PyArray_NBYTES(obj))
+
+#define PyArray_ContiguousFromAny(op, type, min_depth, max_depth) \
+ PyArray_FromAny(op, PyArray_DescrFromType(type), min_depth, \
+ max_depth, NPY_ARRAY_DEFAULT, NULL)
+
+#define PyArray_EquivArrTypes(a1, a2) \
+ PyArray_EquivTypes(PyArray_DESCR(a1), PyArray_DESCR(a2))
+
+#define PyArray_EquivByteorders(b1, b2) \
+ (((b1) == (b2)) || (PyArray_ISNBO(b1) == PyArray_ISNBO(b2)))
+
+#define PyArray_SimpleNew(nd, dims, typenum) \
+ PyArray_New(&PyArray_Type, nd, dims, typenum, NULL, NULL, 0, 0, NULL)
+
+#define PyArray_SimpleNewFromData(nd, dims, typenum, data) \
+ PyArray_New(&PyArray_Type, nd, dims, typenum, NULL, \
+ data, 0, NPY_ARRAY_CARRAY, NULL)
+
+#define PyArray_SimpleNewFromDescr(nd, dims, descr) \
+ PyArray_NewFromDescr(&PyArray_Type, descr, nd, dims, \
+ NULL, NULL, 0, NULL)
+
+#define PyArray_ToScalar(data, arr) \
+ PyArray_Scalar(data, PyArray_DESCR(arr), (PyObject *)arr)
+
+
+/* These might be faster without the dereferencing of obj
+ going on inside -- of course an optimizing compiler should
+ inline the constants inside a for loop making it a moot point
+*/
+
+#define PyArray_GETPTR1(obj, i) ((void *)(PyArray_BYTES(obj) + \
+ (i)*PyArray_STRIDES(obj)[0]))
+
+#define PyArray_GETPTR2(obj, i, j) ((void *)(PyArray_BYTES(obj) + \
+ (i)*PyArray_STRIDES(obj)[0] + \
+ (j)*PyArray_STRIDES(obj)[1]))
+
+#define PyArray_GETPTR3(obj, i, j, k) ((void *)(PyArray_BYTES(obj) + \
+ (i)*PyArray_STRIDES(obj)[0] + \
+ (j)*PyArray_STRIDES(obj)[1] + \
+ (k)*PyArray_STRIDES(obj)[2]))
+
+#define PyArray_GETPTR4(obj, i, j, k, l) ((void *)(PyArray_BYTES(obj) + \
+ (i)*PyArray_STRIDES(obj)[0] + \
+ (j)*PyArray_STRIDES(obj)[1] + \
+ (k)*PyArray_STRIDES(obj)[2] + \
+ (l)*PyArray_STRIDES(obj)[3]))
+
+static inline void
+PyArray_DiscardWritebackIfCopy(PyArrayObject *arr)
+{
+ PyArrayObject_fields *fa = (PyArrayObject_fields *)arr;
+ if (fa && fa->base) {
+ if (fa->flags & NPY_ARRAY_WRITEBACKIFCOPY) {
+ PyArray_ENABLEFLAGS((PyArrayObject*)fa->base, NPY_ARRAY_WRITEABLE);
+ Py_DECREF(fa->base);
+ fa->base = NULL;
+ PyArray_CLEARFLAGS(arr, NPY_ARRAY_WRITEBACKIFCOPY);
+ }
+ }
+}
+
+#define PyArray_DESCR_REPLACE(descr) do { \
+ PyArray_Descr *_new_; \
+ _new_ = PyArray_DescrNew(descr); \
+ Py_XDECREF(descr); \
+ descr = _new_; \
+ } while(0)
+
+/* Copy should always return contiguous array */
+#define PyArray_Copy(obj) PyArray_NewCopy(obj, NPY_CORDER)
+
+#define PyArray_FromObject(op, type, min_depth, max_depth) \
+ PyArray_FromAny(op, PyArray_DescrFromType(type), min_depth, \
+ max_depth, NPY_ARRAY_BEHAVED | \
+ NPY_ARRAY_ENSUREARRAY, NULL)
+
+#define PyArray_ContiguousFromObject(op, type, min_depth, max_depth) \
+ PyArray_FromAny(op, PyArray_DescrFromType(type), min_depth, \
+ max_depth, NPY_ARRAY_DEFAULT | \
+ NPY_ARRAY_ENSUREARRAY, NULL)
+
+#define PyArray_CopyFromObject(op, type, min_depth, max_depth) \
+ PyArray_FromAny(op, PyArray_DescrFromType(type), min_depth, \
+ max_depth, NPY_ARRAY_ENSURECOPY | \
+ NPY_ARRAY_DEFAULT | \
+ NPY_ARRAY_ENSUREARRAY, NULL)
+
+#define PyArray_Cast(mp, type_num) \
+ PyArray_CastToType(mp, PyArray_DescrFromType(type_num), 0)
+
+#define PyArray_Take(ap, items, axis) \
+ PyArray_TakeFrom(ap, items, axis, NULL, NPY_RAISE)
+
+#define PyArray_Put(ap, items, values) \
+ PyArray_PutTo(ap, items, values, NPY_RAISE)
+
+
+/*
+ Check to see if this key in the dictionary is the "title"
+ entry of the tuple (i.e. a duplicate dictionary entry in the fields
+ dict).
+*/
+
+static inline int
+NPY_TITLE_KEY_check(PyObject *key, PyObject *value)
+{
+ PyObject *title;
+ if (PyTuple_Size(value) != 3) {
+ return 0;
+ }
+ title = PyTuple_GetItem(value, 2);
+ if (key == title) {
+ return 1;
+ }
+#ifdef PYPY_VERSION
+ /*
+ * On PyPy, dictionary keys do not always preserve object identity.
+ * Fall back to comparison by value.
+ */
+ if (PyUnicode_Check(title) && PyUnicode_Check(key)) {
+ return PyUnicode_Compare(title, key) == 0 ? 1 : 0;
+ }
+#endif
+ return 0;
+}
+
+/* Macro, for backward compat with "if NPY_TITLE_KEY(key, value) { ..." */
+#define NPY_TITLE_KEY(key, value) (NPY_TITLE_KEY_check((key), (value)))
+
+#define DEPRECATE(msg) PyErr_WarnEx(PyExc_DeprecationWarning,msg,1)
+#define DEPRECATE_FUTUREWARNING(msg) PyErr_WarnEx(PyExc_FutureWarning,msg,1)
+
+
+/*
+ * These macros and functions unfortunately require runtime version checks
+ * that are only defined in `npy_2_compat.h`. For that reasons they cannot be
+ * part of `ndarraytypes.h` which tries to be self contained.
+ */
+
+static inline npy_intp
+PyArray_ITEMSIZE(const PyArrayObject *arr)
+{
+ return PyDataType_ELSIZE(((PyArrayObject_fields *)arr)->descr);
+}
+
+#define PyDataType_HASFIELDS(obj) (PyDataType_ISLEGACY((PyArray_Descr*)(obj)) && PyDataType_NAMES((PyArray_Descr*)(obj)) != NULL)
+#define PyDataType_HASSUBARRAY(dtype) (PyDataType_ISLEGACY(dtype) && PyDataType_SUBARRAY(dtype) != NULL)
+#define PyDataType_ISUNSIZED(dtype) ((dtype)->elsize == 0 && \
+ !PyDataType_HASFIELDS(dtype))
+
+#define PyDataType_FLAGCHK(dtype, flag) \
+ ((PyDataType_FLAGS(dtype) & (flag)) == (flag))
+
+#define PyDataType_REFCHK(dtype) \
+ PyDataType_FLAGCHK(dtype, NPY_ITEM_REFCOUNT)
+
+#define NPY_BEGIN_THREADS_DESCR(dtype) \
+ do {if (!(PyDataType_FLAGCHK((dtype), NPY_NEEDS_PYAPI))) \
+ NPY_BEGIN_THREADS;} while (0);
+
+#define NPY_END_THREADS_DESCR(dtype) \
+ do {if (!(PyDataType_FLAGCHK((dtype), NPY_NEEDS_PYAPI))) \
+ NPY_END_THREADS; } while (0);
+
+#if !(defined(NPY_INTERNAL_BUILD) && NPY_INTERNAL_BUILD)
+/* The internal copy of this is now defined in `dtypemeta.h` */
+/*
+ * `PyArray_Scalar` is the same as this function but converts will convert
+ * most NumPy types to Python scalars.
+ */
+static inline PyObject *
+PyArray_GETITEM(const PyArrayObject *arr, const char *itemptr)
+{
+ return PyDataType_GetArrFuncs(((PyArrayObject_fields *)arr)->descr)->getitem(
+ (void *)itemptr, (PyArrayObject *)arr);
+}
+
+/*
+ * SETITEM should only be used if it is known that the value is a scalar
+ * and of a type understood by the arrays dtype.
+ * Use `PyArray_Pack` if the value may be of a different dtype.
+ */
+static inline int
+PyArray_SETITEM(PyArrayObject *arr, char *itemptr, PyObject *v)
+{
+ return PyDataType_GetArrFuncs(((PyArrayObject_fields *)arr)->descr)->setitem(v, itemptr, arr);
+}
+#endif /* not internal */
+
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif /* NUMPY_CORE_INCLUDE_NUMPY_NDARRAYOBJECT_H_ */
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/ndarraytypes.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/ndarraytypes.h
new file mode 100644
index 0000000000000000000000000000000000000000..37788a74557f4361f78d611470ffe9318f3c8752
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/ndarraytypes.h
@@ -0,0 +1,1933 @@
+#ifndef NUMPY_CORE_INCLUDE_NUMPY_NDARRAYTYPES_H_
+#define NUMPY_CORE_INCLUDE_NUMPY_NDARRAYTYPES_H_
+
+#include "npy_common.h"
+#include "npy_endian.h"
+#include "npy_cpu.h"
+#include "utils.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define NPY_NO_EXPORT NPY_VISIBILITY_HIDDEN
+
+/* Always allow threading unless it was explicitly disabled at build time */
+#if !NPY_NO_SMP
+ #define NPY_ALLOW_THREADS 1
+#else
+ #define NPY_ALLOW_THREADS 0
+#endif
+
+#ifndef __has_extension
+#define __has_extension(x) 0
+#endif
+
+/*
+ * There are several places in the code where an array of dimensions
+ * is allocated statically. This is the size of that static
+ * allocation.
+ *
+ * The array creation itself could have arbitrary dimensions but all
+ * the places where static allocation is used would need to be changed
+ * to dynamic (including inside of several structures)
+ *
+ * As of NumPy 2.0, we strongly discourage the downstream use of NPY_MAXDIMS,
+ * but since auditing everything seems a big ask, define it as 64.
+ * A future version could:
+ * - Increase or remove the limit and require recompilation (like 2.0 did)
+ * - Deprecate or remove the macro but keep the limit (at basically any time)
+ */
+#define NPY_MAXDIMS 64
+/* We cannot change this as it would break ABI: */
+#define NPY_MAXDIMS_LEGACY_ITERS 32
+/* NPY_MAXARGS is version dependent and defined in npy_2_compat.h */
+
+/* Used for Converter Functions "O&" code in ParseTuple */
+#define NPY_FAIL 0
+#define NPY_SUCCEED 1
+
+
+enum NPY_TYPES { 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,
+ /*
+ * New 1.6 types appended, may be integrated
+ * into the above in 2.0.
+ */
+ NPY_DATETIME, NPY_TIMEDELTA, NPY_HALF,
+
+ NPY_CHAR, /* Deprecated, will raise if used */
+
+ /* The number of *legacy* dtypes */
+ NPY_NTYPES_LEGACY=24,
+
+ /* assign a high value to avoid changing this in the
+ future when new dtypes are added */
+ NPY_NOTYPE=25,
+
+ NPY_USERDEF=256, /* leave room for characters */
+
+ /* The number of types not including the new 1.6 types */
+ NPY_NTYPES_ABI_COMPATIBLE=21,
+
+ /*
+ * New DTypes which do not share the legacy layout
+ * (added after NumPy 2.0). VSTRING is the first of these
+ * we may open up a block for user-defined dtypes in the
+ * future.
+ */
+ NPY_VSTRING=2056,
+};
+
+
+/* basetype array priority */
+#define NPY_PRIORITY 0.0
+
+/* default subtype priority */
+#define NPY_SUBTYPE_PRIORITY 1.0
+
+/* default scalar priority */
+#define NPY_SCALAR_PRIORITY -1000000.0
+
+/* How many floating point types are there (excluding half) */
+#define NPY_NUM_FLOATTYPE 3
+
+/*
+ * These characters correspond to the array type and the struct
+ * module
+ */
+
+enum NPY_TYPECHAR {
+ NPY_BOOLLTR = '?',
+ NPY_BYTELTR = 'b',
+ NPY_UBYTELTR = 'B',
+ NPY_SHORTLTR = 'h',
+ NPY_USHORTLTR = 'H',
+ NPY_INTLTR = 'i',
+ NPY_UINTLTR = 'I',
+ NPY_LONGLTR = 'l',
+ NPY_ULONGLTR = 'L',
+ NPY_LONGLONGLTR = 'q',
+ NPY_ULONGLONGLTR = 'Q',
+ NPY_HALFLTR = 'e',
+ NPY_FLOATLTR = 'f',
+ NPY_DOUBLELTR = 'd',
+ NPY_LONGDOUBLELTR = 'g',
+ NPY_CFLOATLTR = 'F',
+ NPY_CDOUBLELTR = 'D',
+ NPY_CLONGDOUBLELTR = 'G',
+ NPY_OBJECTLTR = 'O',
+ NPY_STRINGLTR = 'S',
+ NPY_DEPRECATED_STRINGLTR2 = 'a',
+ NPY_UNICODELTR = 'U',
+ NPY_VOIDLTR = 'V',
+ NPY_DATETIMELTR = 'M',
+ NPY_TIMEDELTALTR = 'm',
+ NPY_CHARLTR = 'c',
+
+ /*
+ * New non-legacy DTypes
+ */
+ NPY_VSTRINGLTR = 'T',
+
+ /*
+ * Note, we removed `NPY_INTPLTR` due to changing its definition
+ * to 'n', rather than 'p'. On any typical platform this is the
+ * same integer. 'n' should be used for the `np.intp` with the same
+ * size as `size_t` while 'p' remains pointer sized.
+ *
+ * 'p', 'P', 'n', and 'N' are valid and defined explicitly
+ * in `arraytypes.c.src`.
+ */
+
+ /*
+ * These are for dtype 'kinds', not dtype 'typecodes'
+ * as the above are for.
+ */
+ NPY_GENBOOLLTR ='b',
+ NPY_SIGNEDLTR = 'i',
+ NPY_UNSIGNEDLTR = 'u',
+ NPY_FLOATINGLTR = 'f',
+ NPY_COMPLEXLTR = 'c',
+
+};
+
+/*
+ * Changing this may break Numpy API compatibility
+ * due to changing offsets in PyArray_ArrFuncs, so be
+ * careful. Here we have reused the mergesort slot for
+ * any kind of stable sort, the actual implementation will
+ * depend on the data type.
+ */
+typedef enum {
+ _NPY_SORT_UNDEFINED=-1,
+ NPY_QUICKSORT=0,
+ NPY_HEAPSORT=1,
+ NPY_MERGESORT=2,
+ NPY_STABLESORT=2,
+} NPY_SORTKIND;
+#define NPY_NSORTS (NPY_STABLESORT + 1)
+
+
+typedef enum {
+ NPY_INTROSELECT=0
+} NPY_SELECTKIND;
+#define NPY_NSELECTS (NPY_INTROSELECT + 1)
+
+
+typedef enum {
+ NPY_SEARCHLEFT=0,
+ NPY_SEARCHRIGHT=1
+} NPY_SEARCHSIDE;
+#define NPY_NSEARCHSIDES (NPY_SEARCHRIGHT + 1)
+
+
+typedef enum {
+ NPY_NOSCALAR=-1,
+ NPY_BOOL_SCALAR,
+ NPY_INTPOS_SCALAR,
+ NPY_INTNEG_SCALAR,
+ NPY_FLOAT_SCALAR,
+ NPY_COMPLEX_SCALAR,
+ NPY_OBJECT_SCALAR
+} NPY_SCALARKIND;
+#define NPY_NSCALARKINDS (NPY_OBJECT_SCALAR + 1)
+
+/* For specifying array memory layout or iteration order */
+typedef enum {
+ /* Fortran order if inputs are all Fortran, C otherwise */
+ NPY_ANYORDER=-1,
+ /* C order */
+ NPY_CORDER=0,
+ /* Fortran order */
+ NPY_FORTRANORDER=1,
+ /* An order as close to the inputs as possible */
+ NPY_KEEPORDER=2
+} NPY_ORDER;
+
+/* For specifying allowed casting in operations which support it */
+typedef enum {
+ _NPY_ERROR_OCCURRED_IN_CAST = -1,
+ /* Only allow identical types */
+ NPY_NO_CASTING=0,
+ /* Allow identical and byte swapped types */
+ NPY_EQUIV_CASTING=1,
+ /* Only allow safe casts */
+ NPY_SAFE_CASTING=2,
+ /* Allow safe casts or casts within the same kind */
+ NPY_SAME_KIND_CASTING=3,
+ /* Allow any casts */
+ NPY_UNSAFE_CASTING=4,
+} NPY_CASTING;
+
+typedef enum {
+ NPY_CLIP=0,
+ NPY_WRAP=1,
+ NPY_RAISE=2
+} NPY_CLIPMODE;
+
+typedef enum {
+ NPY_VALID=0,
+ NPY_SAME=1,
+ NPY_FULL=2
+} NPY_CORRELATEMODE;
+
+/* The special not-a-time (NaT) value */
+#define NPY_DATETIME_NAT NPY_MIN_INT64
+
+/*
+ * Upper bound on the length of a DATETIME ISO 8601 string
+ * YEAR: 21 (64-bit year)
+ * MONTH: 3
+ * DAY: 3
+ * HOURS: 3
+ * MINUTES: 3
+ * SECONDS: 3
+ * ATTOSECONDS: 1 + 3*6
+ * TIMEZONE: 5
+ * NULL TERMINATOR: 1
+ */
+#define NPY_DATETIME_MAX_ISO8601_STRLEN (21 + 3*5 + 1 + 3*6 + 6 + 1)
+
+/* The FR in the unit names stands for frequency */
+typedef enum {
+ /* Force signed enum type, must be -1 for code compatibility */
+ NPY_FR_ERROR = -1, /* error or undetermined */
+
+ /* Start of valid units */
+ NPY_FR_Y = 0, /* Years */
+ NPY_FR_M = 1, /* Months */
+ NPY_FR_W = 2, /* Weeks */
+ /* Gap where 1.6 NPY_FR_B (value 3) was */
+ NPY_FR_D = 4, /* Days */
+ NPY_FR_h = 5, /* hours */
+ NPY_FR_m = 6, /* minutes */
+ NPY_FR_s = 7, /* seconds */
+ NPY_FR_ms = 8, /* milliseconds */
+ NPY_FR_us = 9, /* microseconds */
+ NPY_FR_ns = 10, /* nanoseconds */
+ NPY_FR_ps = 11, /* picoseconds */
+ NPY_FR_fs = 12, /* femtoseconds */
+ NPY_FR_as = 13, /* attoseconds */
+ NPY_FR_GENERIC = 14 /* unbound units, can convert to anything */
+} NPY_DATETIMEUNIT;
+
+/*
+ * NOTE: With the NPY_FR_B gap for 1.6 ABI compatibility, NPY_DATETIME_NUMUNITS
+ * is technically one more than the actual number of units.
+ */
+#define NPY_DATETIME_NUMUNITS (NPY_FR_GENERIC + 1)
+#define NPY_DATETIME_DEFAULTUNIT NPY_FR_GENERIC
+
+/*
+ * Business day conventions for mapping invalid business
+ * days to valid business days.
+ */
+typedef enum {
+ /* Go forward in time to the following business day. */
+ NPY_BUSDAY_FORWARD,
+ NPY_BUSDAY_FOLLOWING = NPY_BUSDAY_FORWARD,
+ /* Go backward in time to the preceding business day. */
+ NPY_BUSDAY_BACKWARD,
+ NPY_BUSDAY_PRECEDING = NPY_BUSDAY_BACKWARD,
+ /*
+ * Go forward in time to the following business day, unless it
+ * crosses a month boundary, in which case go backward
+ */
+ NPY_BUSDAY_MODIFIEDFOLLOWING,
+ /*
+ * Go backward in time to the preceding business day, unless it
+ * crosses a month boundary, in which case go forward.
+ */
+ NPY_BUSDAY_MODIFIEDPRECEDING,
+ /* Produce a NaT for non-business days. */
+ NPY_BUSDAY_NAT,
+ /* Raise an exception for non-business days. */
+ NPY_BUSDAY_RAISE
+} NPY_BUSDAY_ROLL;
+
+
+/************************************************************
+ * NumPy Auxiliary Data for inner loops, sort functions, etc.
+ ************************************************************/
+
+/*
+ * When creating an auxiliary data struct, this should always appear
+ * as the first member, like this:
+ *
+ * typedef struct {
+ * NpyAuxData base;
+ * double constant;
+ * } constant_multiplier_aux_data;
+ */
+typedef struct NpyAuxData_tag NpyAuxData;
+
+/* Function pointers for freeing or cloning auxiliary data */
+typedef void (NpyAuxData_FreeFunc) (NpyAuxData *);
+typedef NpyAuxData *(NpyAuxData_CloneFunc) (NpyAuxData *);
+
+struct NpyAuxData_tag {
+ NpyAuxData_FreeFunc *free;
+ NpyAuxData_CloneFunc *clone;
+ /* To allow for a bit of expansion without breaking the ABI */
+ void *reserved[2];
+};
+
+/* Macros to use for freeing and cloning auxiliary data */
+#define NPY_AUXDATA_FREE(auxdata) \
+ do { \
+ if ((auxdata) != NULL) { \
+ (auxdata)->free(auxdata); \
+ } \
+ } while(0)
+#define NPY_AUXDATA_CLONE(auxdata) \
+ ((auxdata)->clone(auxdata))
+
+#define NPY_ERR(str) fprintf(stderr, #str); fflush(stderr);
+#define NPY_ERR2(str) fprintf(stderr, str); fflush(stderr);
+
+/*
+* Macros to define how array, and dimension/strides data is
+* allocated. These should be made private
+*/
+
+#define NPY_USE_PYMEM 1
+
+
+#if NPY_USE_PYMEM == 1
+/* use the Raw versions which are safe to call with the GIL released */
+#define PyArray_malloc PyMem_RawMalloc
+#define PyArray_free PyMem_RawFree
+#define PyArray_realloc PyMem_RawRealloc
+#else
+#define PyArray_malloc malloc
+#define PyArray_free free
+#define PyArray_realloc realloc
+#endif
+
+/* Dimensions and strides */
+#define PyDimMem_NEW(size) \
+ ((npy_intp *)PyArray_malloc(size*sizeof(npy_intp)))
+
+#define PyDimMem_FREE(ptr) PyArray_free(ptr)
+
+#define PyDimMem_RENEW(ptr,size) \
+ ((npy_intp *)PyArray_realloc(ptr,size*sizeof(npy_intp)))
+
+/* forward declaration */
+struct _PyArray_Descr;
+
+/* These must deal with unaligned and swapped data if necessary */
+typedef PyObject * (PyArray_GetItemFunc) (void *, void *);
+typedef int (PyArray_SetItemFunc)(PyObject *, void *, void *);
+
+typedef void (PyArray_CopySwapNFunc)(void *, npy_intp, void *, npy_intp,
+ npy_intp, int, void *);
+
+typedef void (PyArray_CopySwapFunc)(void *, void *, int, void *);
+typedef npy_bool (PyArray_NonzeroFunc)(void *, void *);
+
+
+/*
+ * These assume aligned and notswapped data -- a buffer will be used
+ * before or contiguous data will be obtained
+ */
+
+typedef int (PyArray_CompareFunc)(const void *, const void *, void *);
+typedef int (PyArray_ArgFunc)(void*, npy_intp, npy_intp*, void *);
+
+typedef void (PyArray_DotFunc)(void *, npy_intp, void *, npy_intp, void *,
+ npy_intp, void *);
+
+typedef void (PyArray_VectorUnaryFunc)(void *, void *, npy_intp, void *,
+ void *);
+
+/*
+ * XXX the ignore argument should be removed next time the API version
+ * is bumped. It used to be the separator.
+ */
+typedef int (PyArray_ScanFunc)(FILE *fp, void *dptr,
+ char *ignore, struct _PyArray_Descr *);
+typedef int (PyArray_FromStrFunc)(char *s, void *dptr, char **endptr,
+ struct _PyArray_Descr *);
+
+typedef int (PyArray_FillFunc)(void *, npy_intp, void *);
+
+typedef int (PyArray_SortFunc)(void *, npy_intp, void *);
+typedef int (PyArray_ArgSortFunc)(void *, npy_intp *, npy_intp, void *);
+
+typedef int (PyArray_FillWithScalarFunc)(void *, npy_intp, void *, void *);
+
+typedef int (PyArray_ScalarKindFunc)(void *);
+
+typedef struct {
+ npy_intp *ptr;
+ int len;
+} PyArray_Dims;
+
+typedef struct {
+ /*
+ * Functions to cast to most other standard types
+ * Can have some NULL entries. The types
+ * DATETIME, TIMEDELTA, and HALF go into the castdict
+ * even though they are built-in.
+ */
+ PyArray_VectorUnaryFunc *cast[NPY_NTYPES_ABI_COMPATIBLE];
+
+ /* The next four functions *cannot* be NULL */
+
+ /*
+ * Functions to get and set items with standard Python types
+ * -- not array scalars
+ */
+ PyArray_GetItemFunc *getitem;
+ PyArray_SetItemFunc *setitem;
+
+ /*
+ * Copy and/or swap data. Memory areas may not overlap
+ * Use memmove first if they might
+ */
+ PyArray_CopySwapNFunc *copyswapn;
+ PyArray_CopySwapFunc *copyswap;
+
+ /*
+ * Function to compare items
+ * Can be NULL
+ */
+ PyArray_CompareFunc *compare;
+
+ /*
+ * Function to select largest
+ * Can be NULL
+ */
+ PyArray_ArgFunc *argmax;
+
+ /*
+ * Function to compute dot product
+ * Can be NULL
+ */
+ PyArray_DotFunc *dotfunc;
+
+ /*
+ * Function to scan an ASCII file and
+ * place a single value plus possible separator
+ * Can be NULL
+ */
+ PyArray_ScanFunc *scanfunc;
+
+ /*
+ * Function to read a single value from a string
+ * and adjust the pointer; Can be NULL
+ */
+ PyArray_FromStrFunc *fromstr;
+
+ /*
+ * Function to determine if data is zero or not
+ * If NULL a default version is
+ * used at Registration time.
+ */
+ PyArray_NonzeroFunc *nonzero;
+
+ /*
+ * Used for arange. Should return 0 on success
+ * and -1 on failure.
+ * Can be NULL.
+ */
+ PyArray_FillFunc *fill;
+
+ /*
+ * Function to fill arrays with scalar values
+ * Can be NULL
+ */
+ PyArray_FillWithScalarFunc *fillwithscalar;
+
+ /*
+ * Sorting functions
+ * Can be NULL
+ */
+ PyArray_SortFunc *sort[NPY_NSORTS];
+ PyArray_ArgSortFunc *argsort[NPY_NSORTS];
+
+ /*
+ * Dictionary of additional casting functions
+ * PyArray_VectorUnaryFuncs
+ * which can be populated to support casting
+ * to other registered types. Can be NULL
+ */
+ PyObject *castdict;
+
+ /*
+ * Functions useful for generalizing
+ * the casting rules.
+ * Can be NULL;
+ */
+ PyArray_ScalarKindFunc *scalarkind;
+ int **cancastscalarkindto;
+ int *cancastto;
+
+ void *_unused1;
+ void *_unused2;
+ void *_unused3;
+
+ /*
+ * Function to select smallest
+ * Can be NULL
+ */
+ PyArray_ArgFunc *argmin;
+
+} PyArray_ArrFuncs;
+
+
+/* The item must be reference counted when it is inserted or extracted. */
+#define NPY_ITEM_REFCOUNT 0x01
+/* Same as needing REFCOUNT */
+#define NPY_ITEM_HASOBJECT 0x01
+/* Convert to list for pickling */
+#define NPY_LIST_PICKLE 0x02
+/* The item is a POINTER */
+#define NPY_ITEM_IS_POINTER 0x04
+/* memory needs to be initialized for this data-type */
+#define NPY_NEEDS_INIT 0x08
+/* operations need Python C-API so don't give-up thread. */
+#define NPY_NEEDS_PYAPI 0x10
+/* Use f.getitem when extracting elements of this data-type */
+#define NPY_USE_GETITEM 0x20
+/* Use f.setitem when setting creating 0-d array from this data-type.*/
+#define NPY_USE_SETITEM 0x40
+/* A sticky flag specifically for structured arrays */
+#define NPY_ALIGNED_STRUCT 0x80
+
+/*
+ *These are inherited for global data-type if any data-types in the
+ * field have them
+ */
+#define NPY_FROM_FIELDS (NPY_NEEDS_INIT | NPY_LIST_PICKLE | \
+ NPY_ITEM_REFCOUNT | NPY_NEEDS_PYAPI)
+
+#define NPY_OBJECT_DTYPE_FLAGS (NPY_LIST_PICKLE | NPY_USE_GETITEM | \
+ NPY_ITEM_IS_POINTER | NPY_ITEM_REFCOUNT | \
+ NPY_NEEDS_INIT | NPY_NEEDS_PYAPI)
+
+#if NPY_FEATURE_VERSION >= NPY_2_0_API_VERSION
+/*
+ * Public version of the Descriptor struct as of 2.x
+ */
+typedef struct _PyArray_Descr {
+ PyObject_HEAD
+ /*
+ * the type object representing an
+ * instance of this type -- should not
+ * be two type_numbers with the same type
+ * object.
+ */
+ PyTypeObject *typeobj;
+ /* kind for this type */
+ char kind;
+ /* unique-character representing this type */
+ char type;
+ /*
+ * '>' (big), '<' (little), '|'
+ * (not-applicable), or '=' (native).
+ */
+ char byteorder;
+ /* Former flags flags space (unused) to ensure type_num is stable. */
+ char _former_flags;
+ /* number representing this type */
+ int type_num;
+ /* Space for dtype instance specific flags. */
+ npy_uint64 flags;
+ /* element size (itemsize) for this type */
+ npy_intp elsize;
+ /* alignment needed for this type */
+ npy_intp alignment;
+ /* metadata dict or NULL */
+ PyObject *metadata;
+ /* Cached hash value (-1 if not yet computed). */
+ npy_hash_t hash;
+ /* Unused slot (must be initialized to NULL) for future use */
+ void *reserved_null[2];
+} PyArray_Descr;
+
+#else /* 1.x and 2.x compatible version (only shared fields): */
+
+typedef struct _PyArray_Descr {
+ PyObject_HEAD
+ PyTypeObject *typeobj;
+ char kind;
+ char type;
+ char byteorder;
+ char _former_flags;
+ int type_num;
+} PyArray_Descr;
+
+/* To access modified fields, define the full 2.0 struct: */
+typedef struct {
+ PyObject_HEAD
+ PyTypeObject *typeobj;
+ char kind;
+ char type;
+ char byteorder;
+ char _former_flags;
+ int type_num;
+ npy_uint64 flags;
+ npy_intp elsize;
+ npy_intp alignment;
+ PyObject *metadata;
+ npy_hash_t hash;
+ void *reserved_null[2];
+} _PyArray_DescrNumPy2;
+
+#endif /* 1.x and 2.x compatible version */
+
+/*
+ * Semi-private struct with additional field of legacy descriptors (must
+ * check NPY_DT_is_legacy before casting/accessing). The struct is also not
+ * valid when running on 1.x (i.e. in public API use).
+ */
+typedef struct {
+ PyObject_HEAD
+ PyTypeObject *typeobj;
+ char kind;
+ char type;
+ char byteorder;
+ char _former_flags;
+ int type_num;
+ npy_uint64 flags;
+ npy_intp elsize;
+ npy_intp alignment;
+ PyObject *metadata;
+ npy_hash_t hash;
+ void *reserved_null[2];
+ struct _arr_descr *subarray;
+ PyObject *fields;
+ PyObject *names;
+ NpyAuxData *c_metadata;
+} _PyArray_LegacyDescr;
+
+
+/*
+ * Umodified PyArray_Descr struct identical to NumPy 1.x. This struct is
+ * used as a prototype for registering a new legacy DType.
+ * It is also used to access the fields in user code running on 1.x.
+ */
+typedef struct {
+ PyObject_HEAD
+ PyTypeObject *typeobj;
+ char kind;
+ char type;
+ char byteorder;
+ char flags;
+ int type_num;
+ int elsize;
+ int alignment;
+ struct _arr_descr *subarray;
+ PyObject *fields;
+ PyObject *names;
+ PyArray_ArrFuncs *f;
+ PyObject *metadata;
+ NpyAuxData *c_metadata;
+ npy_hash_t hash;
+} PyArray_DescrProto;
+
+
+typedef struct _arr_descr {
+ PyArray_Descr *base;
+ PyObject *shape; /* a tuple */
+} PyArray_ArrayDescr;
+
+/*
+ * Memory handler structure for array data.
+ */
+/* The declaration of free differs from PyMemAllocatorEx */
+typedef struct {
+ void *ctx;
+ void* (*malloc) (void *ctx, size_t size);
+ void* (*calloc) (void *ctx, size_t nelem, size_t elsize);
+ void* (*realloc) (void *ctx, void *ptr, size_t new_size);
+ void (*free) (void *ctx, void *ptr, size_t size);
+ /*
+ * This is the end of the version=1 struct. Only add new fields after
+ * this line
+ */
+} PyDataMemAllocator;
+
+typedef struct {
+ char name[127]; /* multiple of 64 to keep the struct aligned */
+ uint8_t version; /* currently 1 */
+ PyDataMemAllocator allocator;
+} PyDataMem_Handler;
+
+
+/*
+ * The main array object structure.
+ *
+ * It has been recommended to use the inline functions defined below
+ * (PyArray_DATA and friends) to access fields here for a number of
+ * releases. Direct access to the members themselves is deprecated.
+ * To ensure that your code does not use deprecated access,
+ * #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
+ * (or NPY_1_8_API_VERSION or higher as required).
+ */
+/* This struct will be moved to a private header in a future release */
+typedef struct tagPyArrayObject_fields {
+ PyObject_HEAD
+ /* Pointer to the raw data buffer */
+ char *data;
+ /* The number of dimensions, also called 'ndim' */
+ int nd;
+ /* The size in each dimension, also called 'shape' */
+ npy_intp *dimensions;
+ /*
+ * Number of bytes to jump to get to the
+ * next element in each dimension
+ */
+ npy_intp *strides;
+ /*
+ * This object is decref'd upon
+ * deletion of array. Except in the
+ * case of WRITEBACKIFCOPY which has
+ * special handling.
+ *
+ * For views it points to the original
+ * array, collapsed so no chains of
+ * views occur.
+ *
+ * For creation from buffer object it
+ * points to an object that should be
+ * decref'd on deletion
+ *
+ * For WRITEBACKIFCOPY flag this is an
+ * array to-be-updated upon calling
+ * PyArray_ResolveWritebackIfCopy
+ */
+ PyObject *base;
+ /* Pointer to type structure */
+ PyArray_Descr *descr;
+ /* Flags describing array -- see below */
+ int flags;
+ /* For weak references */
+ PyObject *weakreflist;
+#if NPY_FEATURE_VERSION >= NPY_1_20_API_VERSION
+ void *_buffer_info; /* private buffer info, tagged to allow warning */
+#endif
+ /*
+ * For malloc/calloc/realloc/free per object
+ */
+#if NPY_FEATURE_VERSION >= NPY_1_22_API_VERSION
+ PyObject *mem_handler;
+#endif
+} PyArrayObject_fields;
+
+/*
+ * To hide the implementation details, we only expose
+ * the Python struct HEAD.
+ */
+#if !defined(NPY_NO_DEPRECATED_API) || \
+ (NPY_NO_DEPRECATED_API < NPY_1_7_API_VERSION)
+/*
+ * Can't put this in npy_deprecated_api.h like the others.
+ * PyArrayObject field access is deprecated as of NumPy 1.7.
+ */
+typedef PyArrayObject_fields PyArrayObject;
+#else
+typedef struct tagPyArrayObject {
+ PyObject_HEAD
+} PyArrayObject;
+#endif
+
+/*
+ * Removed 2020-Nov-25, NumPy 1.20
+ * #define NPY_SIZEOF_PYARRAYOBJECT (sizeof(PyArrayObject_fields))
+ *
+ * The above macro was removed as it gave a false sense of a stable ABI
+ * with respect to the structures size. If you require a runtime constant,
+ * you can use `PyArray_Type.tp_basicsize` instead. Otherwise, please
+ * see the PyArrayObject documentation or ask the NumPy developers for
+ * information on how to correctly replace the macro in a way that is
+ * compatible with multiple NumPy versions.
+ */
+
+/* Mirrors buffer object to ptr */
+
+typedef struct {
+ PyObject_HEAD
+ PyObject *base;
+ void *ptr;
+ npy_intp len;
+ int flags;
+} PyArray_Chunk;
+
+typedef struct {
+ NPY_DATETIMEUNIT base;
+ int num;
+} PyArray_DatetimeMetaData;
+
+typedef struct {
+ NpyAuxData base;
+ PyArray_DatetimeMetaData meta;
+} PyArray_DatetimeDTypeMetaData;
+
+/*
+ * This structure contains an exploded view of a date-time value.
+ * NaT is represented by year == NPY_DATETIME_NAT.
+ */
+typedef struct {
+ npy_int64 year;
+ npy_int32 month, day, hour, min, sec, us, ps, as;
+} npy_datetimestruct;
+
+/* This structure contains an exploded view of a timedelta value */
+typedef struct {
+ npy_int64 day;
+ npy_int32 sec, us, ps, as;
+} npy_timedeltastruct;
+
+typedef int (PyArray_FinalizeFunc)(PyArrayObject *, PyObject *);
+
+/*
+ * Means c-style contiguous (last index varies the fastest). The data
+ * elements right after each other.
+ *
+ * This flag may be requested in constructor functions.
+ * This flag may be tested for in PyArray_FLAGS(arr).
+ */
+#define NPY_ARRAY_C_CONTIGUOUS 0x0001
+
+/*
+ * Set if array is a contiguous Fortran array: the first index varies
+ * the fastest in memory (strides array is reverse of C-contiguous
+ * array)
+ *
+ * This flag may be requested in constructor functions.
+ * This flag may be tested for in PyArray_FLAGS(arr).
+ */
+#define NPY_ARRAY_F_CONTIGUOUS 0x0002
+
+/*
+ * Note: all 0-d arrays are C_CONTIGUOUS and F_CONTIGUOUS. If a
+ * 1-d array is C_CONTIGUOUS it is also F_CONTIGUOUS. Arrays with
+ * more then one dimension can be C_CONTIGUOUS and F_CONTIGUOUS
+ * at the same time if they have either zero or one element.
+ * A higher dimensional array always has the same contiguity flags as
+ * `array.squeeze()`; dimensions with `array.shape[dimension] == 1` are
+ * effectively ignored when checking for contiguity.
+ */
+
+/*
+ * If set, the array owns the data: it will be free'd when the array
+ * is deleted.
+ *
+ * This flag may be tested for in PyArray_FLAGS(arr).
+ */
+#define NPY_ARRAY_OWNDATA 0x0004
+
+/*
+ * An array never has the next four set; they're only used as parameter
+ * flags to the various FromAny functions
+ *
+ * This flag may be requested in constructor functions.
+ */
+
+/* Cause a cast to occur regardless of whether or not it is safe. */
+#define NPY_ARRAY_FORCECAST 0x0010
+
+/*
+ * Always copy the array. Returned arrays are always CONTIGUOUS,
+ * ALIGNED, and WRITEABLE. See also: NPY_ARRAY_ENSURENOCOPY = 0x4000.
+ *
+ * This flag may be requested in constructor functions.
+ */
+#define NPY_ARRAY_ENSURECOPY 0x0020
+
+/*
+ * Make sure the returned array is a base-class ndarray
+ *
+ * This flag may be requested in constructor functions.
+ */
+#define NPY_ARRAY_ENSUREARRAY 0x0040
+
+/*
+ * Make sure that the strides are in units of the element size Needed
+ * for some operations with record-arrays.
+ *
+ * This flag may be requested in constructor functions.
+ */
+#define NPY_ARRAY_ELEMENTSTRIDES 0x0080
+
+/*
+ * Array data is aligned on the appropriate memory address for the type
+ * stored according to how the compiler would align things (e.g., an
+ * array of integers (4 bytes each) starts on a memory address that's
+ * a multiple of 4)
+ *
+ * This flag may be requested in constructor functions.
+ * This flag may be tested for in PyArray_FLAGS(arr).
+ */
+#define NPY_ARRAY_ALIGNED 0x0100
+
+/*
+ * Array data has the native endianness
+ *
+ * This flag may be requested in constructor functions.
+ */
+#define NPY_ARRAY_NOTSWAPPED 0x0200
+
+/*
+ * Array data is writeable
+ *
+ * This flag may be requested in constructor functions.
+ * This flag may be tested for in PyArray_FLAGS(arr).
+ */
+#define NPY_ARRAY_WRITEABLE 0x0400
+
+/*
+ * If this flag is set, then base contains a pointer to an array of
+ * the same size that should be updated with the current contents of
+ * this array when PyArray_ResolveWritebackIfCopy is called.
+ *
+ * This flag may be requested in constructor functions.
+ * This flag may be tested for in PyArray_FLAGS(arr).
+ */
+#define NPY_ARRAY_WRITEBACKIFCOPY 0x2000
+
+/*
+ * No copy may be made while converting from an object/array (result is a view)
+ *
+ * This flag may be requested in constructor functions.
+ */
+#define NPY_ARRAY_ENSURENOCOPY 0x4000
+
+/*
+ * NOTE: there are also internal flags defined in multiarray/arrayobject.h,
+ * which start at bit 31 and work down.
+ */
+
+#define NPY_ARRAY_BEHAVED (NPY_ARRAY_ALIGNED | \
+ NPY_ARRAY_WRITEABLE)
+#define NPY_ARRAY_BEHAVED_NS (NPY_ARRAY_ALIGNED | \
+ NPY_ARRAY_WRITEABLE | \
+ NPY_ARRAY_NOTSWAPPED)
+#define NPY_ARRAY_CARRAY (NPY_ARRAY_C_CONTIGUOUS | \
+ NPY_ARRAY_BEHAVED)
+#define NPY_ARRAY_CARRAY_RO (NPY_ARRAY_C_CONTIGUOUS | \
+ NPY_ARRAY_ALIGNED)
+#define NPY_ARRAY_FARRAY (NPY_ARRAY_F_CONTIGUOUS | \
+ NPY_ARRAY_BEHAVED)
+#define NPY_ARRAY_FARRAY_RO (NPY_ARRAY_F_CONTIGUOUS | \
+ NPY_ARRAY_ALIGNED)
+#define NPY_ARRAY_DEFAULT (NPY_ARRAY_CARRAY)
+#define NPY_ARRAY_IN_ARRAY (NPY_ARRAY_CARRAY_RO)
+#define NPY_ARRAY_OUT_ARRAY (NPY_ARRAY_CARRAY)
+#define NPY_ARRAY_INOUT_ARRAY (NPY_ARRAY_CARRAY)
+#define NPY_ARRAY_INOUT_ARRAY2 (NPY_ARRAY_CARRAY | \
+ NPY_ARRAY_WRITEBACKIFCOPY)
+#define NPY_ARRAY_IN_FARRAY (NPY_ARRAY_FARRAY_RO)
+#define NPY_ARRAY_OUT_FARRAY (NPY_ARRAY_FARRAY)
+#define NPY_ARRAY_INOUT_FARRAY (NPY_ARRAY_FARRAY)
+#define NPY_ARRAY_INOUT_FARRAY2 (NPY_ARRAY_FARRAY | \
+ NPY_ARRAY_WRITEBACKIFCOPY)
+
+#define NPY_ARRAY_UPDATE_ALL (NPY_ARRAY_C_CONTIGUOUS | \
+ NPY_ARRAY_F_CONTIGUOUS | \
+ NPY_ARRAY_ALIGNED)
+
+/* This flag is for the array interface, not PyArrayObject */
+#define NPY_ARR_HAS_DESCR 0x0800
+
+
+
+
+/*
+ * Size of internal buffers used for alignment Make BUFSIZE a multiple
+ * of sizeof(npy_cdouble) -- usually 16 so that ufunc buffers are aligned
+ */
+#define NPY_MIN_BUFSIZE ((int)sizeof(npy_cdouble))
+#define NPY_MAX_BUFSIZE (((int)sizeof(npy_cdouble))*1000000)
+#define NPY_BUFSIZE 8192
+/* buffer stress test size: */
+/*#define NPY_BUFSIZE 17*/
+
+/*
+ * C API: consists of Macros and functions. The MACROS are defined
+ * here.
+ */
+
+
+#define PyArray_ISCONTIGUOUS(m) PyArray_CHKFLAGS((m), NPY_ARRAY_C_CONTIGUOUS)
+#define PyArray_ISWRITEABLE(m) PyArray_CHKFLAGS((m), NPY_ARRAY_WRITEABLE)
+#define PyArray_ISALIGNED(m) PyArray_CHKFLAGS((m), NPY_ARRAY_ALIGNED)
+
+#define PyArray_IS_C_CONTIGUOUS(m) PyArray_CHKFLAGS((m), NPY_ARRAY_C_CONTIGUOUS)
+#define PyArray_IS_F_CONTIGUOUS(m) PyArray_CHKFLAGS((m), NPY_ARRAY_F_CONTIGUOUS)
+
+/* the variable is used in some places, so always define it */
+#define NPY_BEGIN_THREADS_DEF PyThreadState *_save=NULL;
+#if NPY_ALLOW_THREADS
+#define NPY_BEGIN_ALLOW_THREADS Py_BEGIN_ALLOW_THREADS
+#define NPY_END_ALLOW_THREADS Py_END_ALLOW_THREADS
+#define NPY_BEGIN_THREADS do {_save = PyEval_SaveThread();} while (0);
+#define NPY_END_THREADS do { if (_save) \
+ { PyEval_RestoreThread(_save); _save = NULL;} } while (0);
+#define NPY_BEGIN_THREADS_THRESHOLDED(loop_size) do { if ((loop_size) > 500) \
+ { _save = PyEval_SaveThread();} } while (0);
+
+
+#define NPY_ALLOW_C_API_DEF PyGILState_STATE __save__;
+#define NPY_ALLOW_C_API do {__save__ = PyGILState_Ensure();} while (0);
+#define NPY_DISABLE_C_API do {PyGILState_Release(__save__);} while (0);
+#else
+#define NPY_BEGIN_ALLOW_THREADS
+#define NPY_END_ALLOW_THREADS
+#define NPY_BEGIN_THREADS
+#define NPY_END_THREADS
+#define NPY_BEGIN_THREADS_THRESHOLDED(loop_size)
+#define NPY_BEGIN_THREADS_DESCR(dtype)
+#define NPY_END_THREADS_DESCR(dtype)
+#define NPY_ALLOW_C_API_DEF
+#define NPY_ALLOW_C_API
+#define NPY_DISABLE_C_API
+#endif
+
+/**********************************
+ * The nditer object, added in 1.6
+ **********************************/
+
+/* The actual structure of the iterator is an internal detail */
+typedef struct NpyIter_InternalOnly NpyIter;
+
+/* Iterator function pointers that may be specialized */
+typedef int (NpyIter_IterNextFunc)(NpyIter *iter);
+typedef void (NpyIter_GetMultiIndexFunc)(NpyIter *iter,
+ npy_intp *outcoords);
+
+/*** Global flags that may be passed to the iterator constructors ***/
+
+/* Track an index representing C order */
+#define NPY_ITER_C_INDEX 0x00000001
+/* Track an index representing Fortran order */
+#define NPY_ITER_F_INDEX 0x00000002
+/* Track a multi-index */
+#define NPY_ITER_MULTI_INDEX 0x00000004
+/* User code external to the iterator does the 1-dimensional innermost loop */
+#define NPY_ITER_EXTERNAL_LOOP 0x00000008
+/* Convert all the operands to a common data type */
+#define NPY_ITER_COMMON_DTYPE 0x00000010
+/* Operands may hold references, requiring API access during iteration */
+#define NPY_ITER_REFS_OK 0x00000020
+/* Zero-sized operands should be permitted, iteration checks IterSize for 0 */
+#define NPY_ITER_ZEROSIZE_OK 0x00000040
+/* Permits reductions (size-0 stride with dimension size > 1) */
+#define NPY_ITER_REDUCE_OK 0x00000080
+/* Enables sub-range iteration */
+#define NPY_ITER_RANGED 0x00000100
+/* Enables buffering */
+#define NPY_ITER_BUFFERED 0x00000200
+/* When buffering is enabled, grows the inner loop if possible */
+#define NPY_ITER_GROWINNER 0x00000400
+/* Delay allocation of buffers until first Reset* call */
+#define NPY_ITER_DELAY_BUFALLOC 0x00000800
+/* When NPY_KEEPORDER is specified, disable reversing negative-stride axes */
+#define NPY_ITER_DONT_NEGATE_STRIDES 0x00001000
+/*
+ * If output operands overlap with other operands (based on heuristics that
+ * has false positives but no false negatives), make temporary copies to
+ * eliminate overlap.
+ */
+#define NPY_ITER_COPY_IF_OVERLAP 0x00002000
+
+/*** Per-operand flags that may be passed to the iterator constructors ***/
+
+/* The operand will be read from and written to */
+#define NPY_ITER_READWRITE 0x00010000
+/* The operand will only be read from */
+#define NPY_ITER_READONLY 0x00020000
+/* The operand will only be written to */
+#define NPY_ITER_WRITEONLY 0x00040000
+/* The operand's data must be in native byte order */
+#define NPY_ITER_NBO 0x00080000
+/* The operand's data must be aligned */
+#define NPY_ITER_ALIGNED 0x00100000
+/* The operand's data must be contiguous (within the inner loop) */
+#define NPY_ITER_CONTIG 0x00200000
+/* The operand may be copied to satisfy requirements */
+#define NPY_ITER_COPY 0x00400000
+/* The operand may be copied with WRITEBACKIFCOPY to satisfy requirements */
+#define NPY_ITER_UPDATEIFCOPY 0x00800000
+/* Allocate the operand if it is NULL */
+#define NPY_ITER_ALLOCATE 0x01000000
+/* If an operand is allocated, don't use any subtype */
+#define NPY_ITER_NO_SUBTYPE 0x02000000
+/* This is a virtual array slot, operand is NULL but temporary data is there */
+#define NPY_ITER_VIRTUAL 0x04000000
+/* Require that the dimension match the iterator dimensions exactly */
+#define NPY_ITER_NO_BROADCAST 0x08000000
+/* A mask is being used on this array, affects buffer -> array copy */
+#define NPY_ITER_WRITEMASKED 0x10000000
+/* This array is the mask for all WRITEMASKED operands */
+#define NPY_ITER_ARRAYMASK 0x20000000
+/* Assume iterator order data access for COPY_IF_OVERLAP */
+#define NPY_ITER_OVERLAP_ASSUME_ELEMENTWISE 0x40000000
+
+#define NPY_ITER_GLOBAL_FLAGS 0x0000ffff
+#define NPY_ITER_PER_OP_FLAGS 0xffff0000
+
+
+/*****************************
+ * Basic iterator object
+ *****************************/
+
+/* FWD declaration */
+typedef struct PyArrayIterObject_tag PyArrayIterObject;
+
+/*
+ * type of the function which translates a set of coordinates to a
+ * pointer to the data
+ */
+typedef char* (*npy_iter_get_dataptr_t)(
+ PyArrayIterObject* iter, const npy_intp*);
+
+struct PyArrayIterObject_tag {
+ PyObject_HEAD
+ int nd_m1; /* number of dimensions - 1 */
+ npy_intp index, size;
+ npy_intp coordinates[NPY_MAXDIMS_LEGACY_ITERS];/* N-dimensional loop */
+ npy_intp dims_m1[NPY_MAXDIMS_LEGACY_ITERS]; /* ao->dimensions - 1 */
+ npy_intp strides[NPY_MAXDIMS_LEGACY_ITERS]; /* ao->strides or fake */
+ npy_intp backstrides[NPY_MAXDIMS_LEGACY_ITERS];/* how far to jump back */
+ npy_intp factors[NPY_MAXDIMS_LEGACY_ITERS]; /* shape factors */
+ PyArrayObject *ao;
+ char *dataptr; /* pointer to current item*/
+ npy_bool contiguous;
+
+ npy_intp bounds[NPY_MAXDIMS_LEGACY_ITERS][2];
+ npy_intp limits[NPY_MAXDIMS_LEGACY_ITERS][2];
+ npy_intp limits_sizes[NPY_MAXDIMS_LEGACY_ITERS];
+ npy_iter_get_dataptr_t translate;
+} ;
+
+
+/* Iterator API */
+#define PyArrayIter_Check(op) PyObject_TypeCheck((op), &PyArrayIter_Type)
+
+#define _PyAIT(it) ((PyArrayIterObject *)(it))
+#define PyArray_ITER_RESET(it) do { \
+ _PyAIT(it)->index = 0; \
+ _PyAIT(it)->dataptr = PyArray_BYTES(_PyAIT(it)->ao); \
+ memset(_PyAIT(it)->coordinates, 0, \
+ (_PyAIT(it)->nd_m1+1)*sizeof(npy_intp)); \
+} while (0)
+
+#define _PyArray_ITER_NEXT1(it) do { \
+ (it)->dataptr += _PyAIT(it)->strides[0]; \
+ (it)->coordinates[0]++; \
+} while (0)
+
+#define _PyArray_ITER_NEXT2(it) do { \
+ if ((it)->coordinates[1] < (it)->dims_m1[1]) { \
+ (it)->coordinates[1]++; \
+ (it)->dataptr += (it)->strides[1]; \
+ } \
+ else { \
+ (it)->coordinates[1] = 0; \
+ (it)->coordinates[0]++; \
+ (it)->dataptr += (it)->strides[0] - \
+ (it)->backstrides[1]; \
+ } \
+} while (0)
+
+#define PyArray_ITER_NEXT(it) do { \
+ _PyAIT(it)->index++; \
+ if (_PyAIT(it)->nd_m1 == 0) { \
+ _PyArray_ITER_NEXT1(_PyAIT(it)); \
+ } \
+ else if (_PyAIT(it)->contiguous) \
+ _PyAIT(it)->dataptr += PyArray_ITEMSIZE(_PyAIT(it)->ao); \
+ else if (_PyAIT(it)->nd_m1 == 1) { \
+ _PyArray_ITER_NEXT2(_PyAIT(it)); \
+ } \
+ else { \
+ int __npy_i; \
+ for (__npy_i=_PyAIT(it)->nd_m1; __npy_i >= 0; __npy_i--) { \
+ if (_PyAIT(it)->coordinates[__npy_i] < \
+ _PyAIT(it)->dims_m1[__npy_i]) { \
+ _PyAIT(it)->coordinates[__npy_i]++; \
+ _PyAIT(it)->dataptr += \
+ _PyAIT(it)->strides[__npy_i]; \
+ break; \
+ } \
+ else { \
+ _PyAIT(it)->coordinates[__npy_i] = 0; \
+ _PyAIT(it)->dataptr -= \
+ _PyAIT(it)->backstrides[__npy_i]; \
+ } \
+ } \
+ } \
+} while (0)
+
+#define PyArray_ITER_GOTO(it, destination) do { \
+ int __npy_i; \
+ _PyAIT(it)->index = 0; \
+ _PyAIT(it)->dataptr = PyArray_BYTES(_PyAIT(it)->ao); \
+ for (__npy_i = _PyAIT(it)->nd_m1; __npy_i>=0; __npy_i--) { \
+ if (destination[__npy_i] < 0) { \
+ destination[__npy_i] += \
+ _PyAIT(it)->dims_m1[__npy_i]+1; \
+ } \
+ _PyAIT(it)->dataptr += destination[__npy_i] * \
+ _PyAIT(it)->strides[__npy_i]; \
+ _PyAIT(it)->coordinates[__npy_i] = \
+ destination[__npy_i]; \
+ _PyAIT(it)->index += destination[__npy_i] * \
+ ( __npy_i==_PyAIT(it)->nd_m1 ? 1 : \
+ _PyAIT(it)->dims_m1[__npy_i+1]+1) ; \
+ } \
+} while (0)
+
+#define PyArray_ITER_GOTO1D(it, ind) do { \
+ int __npy_i; \
+ npy_intp __npy_ind = (npy_intp)(ind); \
+ if (__npy_ind < 0) __npy_ind += _PyAIT(it)->size; \
+ _PyAIT(it)->index = __npy_ind; \
+ if (_PyAIT(it)->nd_m1 == 0) { \
+ _PyAIT(it)->dataptr = PyArray_BYTES(_PyAIT(it)->ao) + \
+ __npy_ind * _PyAIT(it)->strides[0]; \
+ } \
+ else if (_PyAIT(it)->contiguous) \
+ _PyAIT(it)->dataptr = PyArray_BYTES(_PyAIT(it)->ao) + \
+ __npy_ind * PyArray_ITEMSIZE(_PyAIT(it)->ao); \
+ else { \
+ _PyAIT(it)->dataptr = PyArray_BYTES(_PyAIT(it)->ao); \
+ for (__npy_i = 0; __npy_i<=_PyAIT(it)->nd_m1; \
+ __npy_i++) { \
+ _PyAIT(it)->coordinates[__npy_i] = \
+ (__npy_ind / _PyAIT(it)->factors[__npy_i]); \
+ _PyAIT(it)->dataptr += \
+ (__npy_ind / _PyAIT(it)->factors[__npy_i]) \
+ * _PyAIT(it)->strides[__npy_i]; \
+ __npy_ind %= _PyAIT(it)->factors[__npy_i]; \
+ } \
+ } \
+} while (0)
+
+#define PyArray_ITER_DATA(it) ((void *)(_PyAIT(it)->dataptr))
+
+#define PyArray_ITER_NOTDONE(it) (_PyAIT(it)->index < _PyAIT(it)->size)
+
+
+/*
+ * Any object passed to PyArray_Broadcast must be binary compatible
+ * with this structure.
+ */
+
+typedef struct {
+ PyObject_HEAD
+ int numiter; /* number of iters */
+ npy_intp size; /* broadcasted size */
+ npy_intp index; /* current index */
+ int nd; /* number of dims */
+ npy_intp dimensions[NPY_MAXDIMS_LEGACY_ITERS]; /* dimensions */
+ /*
+ * Space for the individual iterators, do not specify size publicly
+ * to allow changing it more easily.
+ * One reason is that Cython uses this for checks and only allows
+ * growing structs (as of Cython 3.0.6). It also allows NPY_MAXARGS
+ * to be runtime dependent.
+ */
+#if (defined(NPY_INTERNAL_BUILD) && NPY_INTERNAL_BUILD)
+ PyArrayIterObject *iters[64];
+#elif defined(__cplusplus)
+ /*
+ * C++ doesn't strictly support flexible members and gives compilers
+ * warnings (pedantic only), so we lie. We can't make it 64 because
+ * then Cython is unhappy (larger struct at runtime is OK smaller not).
+ */
+ PyArrayIterObject *iters[32];
+#else
+ PyArrayIterObject *iters[];
+#endif
+} PyArrayMultiIterObject;
+
+#define _PyMIT(m) ((PyArrayMultiIterObject *)(m))
+#define PyArray_MultiIter_RESET(multi) do { \
+ int __npy_mi; \
+ _PyMIT(multi)->index = 0; \
+ for (__npy_mi=0; __npy_mi < _PyMIT(multi)->numiter; __npy_mi++) { \
+ PyArray_ITER_RESET(_PyMIT(multi)->iters[__npy_mi]); \
+ } \
+} while (0)
+
+#define PyArray_MultiIter_NEXT(multi) do { \
+ int __npy_mi; \
+ _PyMIT(multi)->index++; \
+ for (__npy_mi=0; __npy_mi < _PyMIT(multi)->numiter; __npy_mi++) { \
+ PyArray_ITER_NEXT(_PyMIT(multi)->iters[__npy_mi]); \
+ } \
+} while (0)
+
+#define PyArray_MultiIter_GOTO(multi, dest) do { \
+ int __npy_mi; \
+ for (__npy_mi=0; __npy_mi < _PyMIT(multi)->numiter; __npy_mi++) { \
+ PyArray_ITER_GOTO(_PyMIT(multi)->iters[__npy_mi], dest); \
+ } \
+ _PyMIT(multi)->index = _PyMIT(multi)->iters[0]->index; \
+} while (0)
+
+#define PyArray_MultiIter_GOTO1D(multi, ind) do { \
+ int __npy_mi; \
+ for (__npy_mi=0; __npy_mi < _PyMIT(multi)->numiter; __npy_mi++) { \
+ PyArray_ITER_GOTO1D(_PyMIT(multi)->iters[__npy_mi], ind); \
+ } \
+ _PyMIT(multi)->index = _PyMIT(multi)->iters[0]->index; \
+} while (0)
+
+#define PyArray_MultiIter_DATA(multi, i) \
+ ((void *)(_PyMIT(multi)->iters[i]->dataptr))
+
+#define PyArray_MultiIter_NEXTi(multi, i) \
+ PyArray_ITER_NEXT(_PyMIT(multi)->iters[i])
+
+#define PyArray_MultiIter_NOTDONE(multi) \
+ (_PyMIT(multi)->index < _PyMIT(multi)->size)
+
+
+static NPY_INLINE int
+PyArray_MultiIter_NUMITER(PyArrayMultiIterObject *multi)
+{
+ return multi->numiter;
+}
+
+
+static NPY_INLINE npy_intp
+PyArray_MultiIter_SIZE(PyArrayMultiIterObject *multi)
+{
+ return multi->size;
+}
+
+
+static NPY_INLINE npy_intp
+PyArray_MultiIter_INDEX(PyArrayMultiIterObject *multi)
+{
+ return multi->index;
+}
+
+
+static NPY_INLINE int
+PyArray_MultiIter_NDIM(PyArrayMultiIterObject *multi)
+{
+ return multi->nd;
+}
+
+
+static NPY_INLINE npy_intp *
+PyArray_MultiIter_DIMS(PyArrayMultiIterObject *multi)
+{
+ return multi->dimensions;
+}
+
+
+static NPY_INLINE void **
+PyArray_MultiIter_ITERS(PyArrayMultiIterObject *multi)
+{
+ return (void**)multi->iters;
+}
+
+
+enum {
+ NPY_NEIGHBORHOOD_ITER_ZERO_PADDING,
+ NPY_NEIGHBORHOOD_ITER_ONE_PADDING,
+ NPY_NEIGHBORHOOD_ITER_CONSTANT_PADDING,
+ NPY_NEIGHBORHOOD_ITER_CIRCULAR_PADDING,
+ NPY_NEIGHBORHOOD_ITER_MIRROR_PADDING
+};
+
+typedef struct {
+ PyObject_HEAD
+
+ /*
+ * PyArrayIterObject part: keep this in this exact order
+ */
+ int nd_m1; /* number of dimensions - 1 */
+ npy_intp index, size;
+ npy_intp coordinates[NPY_MAXDIMS_LEGACY_ITERS];/* N-dimensional loop */
+ npy_intp dims_m1[NPY_MAXDIMS_LEGACY_ITERS]; /* ao->dimensions - 1 */
+ npy_intp strides[NPY_MAXDIMS_LEGACY_ITERS]; /* ao->strides or fake */
+ npy_intp backstrides[NPY_MAXDIMS_LEGACY_ITERS];/* how far to jump back */
+ npy_intp factors[NPY_MAXDIMS_LEGACY_ITERS]; /* shape factors */
+ PyArrayObject *ao;
+ char *dataptr; /* pointer to current item*/
+ npy_bool contiguous;
+
+ npy_intp bounds[NPY_MAXDIMS_LEGACY_ITERS][2];
+ npy_intp limits[NPY_MAXDIMS_LEGACY_ITERS][2];
+ npy_intp limits_sizes[NPY_MAXDIMS_LEGACY_ITERS];
+ npy_iter_get_dataptr_t translate;
+
+ /*
+ * New members
+ */
+ npy_intp nd;
+
+ /* Dimensions is the dimension of the array */
+ npy_intp dimensions[NPY_MAXDIMS_LEGACY_ITERS];
+
+ /*
+ * Neighborhood points coordinates are computed relatively to the
+ * point pointed by _internal_iter
+ */
+ PyArrayIterObject* _internal_iter;
+ /*
+ * To keep a reference to the representation of the constant value
+ * for constant padding
+ */
+ char* constant;
+
+ int mode;
+} PyArrayNeighborhoodIterObject;
+
+/*
+ * Neighborhood iterator API
+ */
+
+/* General: those work for any mode */
+static inline int
+PyArrayNeighborhoodIter_Reset(PyArrayNeighborhoodIterObject* iter);
+static inline int
+PyArrayNeighborhoodIter_Next(PyArrayNeighborhoodIterObject* iter);
+#if 0
+static inline int
+PyArrayNeighborhoodIter_Next2D(PyArrayNeighborhoodIterObject* iter);
+#endif
+
+/*
+ * Include inline implementations - functions defined there are not
+ * considered public API
+ */
+#define NUMPY_CORE_INCLUDE_NUMPY__NEIGHBORHOOD_IMP_H_
+#include "_neighborhood_iterator_imp.h"
+#undef NUMPY_CORE_INCLUDE_NUMPY__NEIGHBORHOOD_IMP_H_
+
+
+
+/* The default array type */
+#define NPY_DEFAULT_TYPE NPY_DOUBLE
+/* default integer type defined in npy_2_compat header */
+
+/*
+ * All sorts of useful ways to look into a PyArrayObject. It is recommended
+ * to use PyArrayObject * objects instead of always casting from PyObject *,
+ * for improved type checking.
+ *
+ * In many cases here the macro versions of the accessors are deprecated,
+ * but can't be immediately changed to inline functions because the
+ * preexisting macros accept PyObject * and do automatic casts. Inline
+ * functions accepting PyArrayObject * provides for some compile-time
+ * checking of correctness when working with these objects in C.
+ */
+
+#define PyArray_ISONESEGMENT(m) (PyArray_CHKFLAGS(m, NPY_ARRAY_C_CONTIGUOUS) || \
+ PyArray_CHKFLAGS(m, NPY_ARRAY_F_CONTIGUOUS))
+
+#define PyArray_ISFORTRAN(m) (PyArray_CHKFLAGS(m, NPY_ARRAY_F_CONTIGUOUS) && \
+ (!PyArray_CHKFLAGS(m, NPY_ARRAY_C_CONTIGUOUS)))
+
+#define PyArray_FORTRAN_IF(m) ((PyArray_CHKFLAGS(m, NPY_ARRAY_F_CONTIGUOUS) ? \
+ NPY_ARRAY_F_CONTIGUOUS : 0))
+
+static inline int
+PyArray_NDIM(const PyArrayObject *arr)
+{
+ return ((PyArrayObject_fields *)arr)->nd;
+}
+
+static inline void *
+PyArray_DATA(const PyArrayObject *arr)
+{
+ return ((PyArrayObject_fields *)arr)->data;
+}
+
+static inline char *
+PyArray_BYTES(const PyArrayObject *arr)
+{
+ return ((PyArrayObject_fields *)arr)->data;
+}
+
+static inline npy_intp *
+PyArray_DIMS(const PyArrayObject *arr)
+{
+ return ((PyArrayObject_fields *)arr)->dimensions;
+}
+
+static inline npy_intp *
+PyArray_STRIDES(const PyArrayObject *arr)
+{
+ return ((PyArrayObject_fields *)arr)->strides;
+}
+
+static inline npy_intp
+PyArray_DIM(const PyArrayObject *arr, int idim)
+{
+ return ((PyArrayObject_fields *)arr)->dimensions[idim];
+}
+
+static inline npy_intp
+PyArray_STRIDE(const PyArrayObject *arr, int istride)
+{
+ return ((PyArrayObject_fields *)arr)->strides[istride];
+}
+
+static inline NPY_RETURNS_BORROWED_REF PyObject *
+PyArray_BASE(const PyArrayObject *arr)
+{
+ return ((PyArrayObject_fields *)arr)->base;
+}
+
+static inline NPY_RETURNS_BORROWED_REF PyArray_Descr *
+PyArray_DESCR(const PyArrayObject *arr)
+{
+ return ((PyArrayObject_fields *)arr)->descr;
+}
+
+static inline int
+PyArray_FLAGS(const PyArrayObject *arr)
+{
+ return ((PyArrayObject_fields *)arr)->flags;
+}
+
+
+static inline int
+PyArray_TYPE(const PyArrayObject *arr)
+{
+ return ((PyArrayObject_fields *)arr)->descr->type_num;
+}
+
+static inline int
+PyArray_CHKFLAGS(const PyArrayObject *arr, int flags)
+{
+ return (PyArray_FLAGS(arr) & flags) == flags;
+}
+
+static inline PyArray_Descr *
+PyArray_DTYPE(const PyArrayObject *arr)
+{
+ return ((PyArrayObject_fields *)arr)->descr;
+}
+
+static inline npy_intp *
+PyArray_SHAPE(const PyArrayObject *arr)
+{
+ return ((PyArrayObject_fields *)arr)->dimensions;
+}
+
+/*
+ * Enables the specified array flags. Does no checking,
+ * assumes you know what you're doing.
+ */
+static inline void
+PyArray_ENABLEFLAGS(PyArrayObject *arr, int flags)
+{
+ ((PyArrayObject_fields *)arr)->flags |= flags;
+}
+
+/*
+ * Clears the specified array flags. Does no checking,
+ * assumes you know what you're doing.
+ */
+static inline void
+PyArray_CLEARFLAGS(PyArrayObject *arr, int flags)
+{
+ ((PyArrayObject_fields *)arr)->flags &= ~flags;
+}
+
+#if NPY_FEATURE_VERSION >= NPY_1_22_API_VERSION
+ static inline NPY_RETURNS_BORROWED_REF PyObject *
+ PyArray_HANDLER(PyArrayObject *arr)
+ {
+ return ((PyArrayObject_fields *)arr)->mem_handler;
+ }
+#endif
+
+#define PyTypeNum_ISBOOL(type) ((type) == NPY_BOOL)
+
+#define PyTypeNum_ISUNSIGNED(type) (((type) == NPY_UBYTE) || \
+ ((type) == NPY_USHORT) || \
+ ((type) == NPY_UINT) || \
+ ((type) == NPY_ULONG) || \
+ ((type) == NPY_ULONGLONG))
+
+#define PyTypeNum_ISSIGNED(type) (((type) == NPY_BYTE) || \
+ ((type) == NPY_SHORT) || \
+ ((type) == NPY_INT) || \
+ ((type) == NPY_LONG) || \
+ ((type) == NPY_LONGLONG))
+
+#define PyTypeNum_ISINTEGER(type) (((type) >= NPY_BYTE) && \
+ ((type) <= NPY_ULONGLONG))
+
+#define PyTypeNum_ISFLOAT(type) ((((type) >= NPY_FLOAT) && \
+ ((type) <= NPY_LONGDOUBLE)) || \
+ ((type) == NPY_HALF))
+
+#define PyTypeNum_ISNUMBER(type) (((type) <= NPY_CLONGDOUBLE) || \
+ ((type) == NPY_HALF))
+
+#define PyTypeNum_ISSTRING(type) (((type) == NPY_STRING) || \
+ ((type) == NPY_UNICODE))
+
+#define PyTypeNum_ISCOMPLEX(type) (((type) >= NPY_CFLOAT) && \
+ ((type) <= NPY_CLONGDOUBLE))
+
+#define PyTypeNum_ISFLEXIBLE(type) (((type) >=NPY_STRING) && \
+ ((type) <=NPY_VOID))
+
+#define PyTypeNum_ISDATETIME(type) (((type) >=NPY_DATETIME) && \
+ ((type) <=NPY_TIMEDELTA))
+
+#define PyTypeNum_ISUSERDEF(type) (((type) >= NPY_USERDEF) && \
+ ((type) < NPY_USERDEF+ \
+ NPY_NUMUSERTYPES))
+
+#define PyTypeNum_ISEXTENDED(type) (PyTypeNum_ISFLEXIBLE(type) || \
+ PyTypeNum_ISUSERDEF(type))
+
+#define PyTypeNum_ISOBJECT(type) ((type) == NPY_OBJECT)
+
+
+#define PyDataType_ISLEGACY(dtype) ((dtype)->type_num < NPY_VSTRING && ((dtype)->type_num >= 0))
+#define PyDataType_ISBOOL(obj) PyTypeNum_ISBOOL(((PyArray_Descr*)(obj))->type_num)
+#define PyDataType_ISUNSIGNED(obj) PyTypeNum_ISUNSIGNED(((PyArray_Descr*)(obj))->type_num)
+#define PyDataType_ISSIGNED(obj) PyTypeNum_ISSIGNED(((PyArray_Descr*)(obj))->type_num)
+#define PyDataType_ISINTEGER(obj) PyTypeNum_ISINTEGER(((PyArray_Descr*)(obj))->type_num )
+#define PyDataType_ISFLOAT(obj) PyTypeNum_ISFLOAT(((PyArray_Descr*)(obj))->type_num)
+#define PyDataType_ISNUMBER(obj) PyTypeNum_ISNUMBER(((PyArray_Descr*)(obj))->type_num)
+#define PyDataType_ISSTRING(obj) PyTypeNum_ISSTRING(((PyArray_Descr*)(obj))->type_num)
+#define PyDataType_ISCOMPLEX(obj) PyTypeNum_ISCOMPLEX(((PyArray_Descr*)(obj))->type_num)
+#define PyDataType_ISFLEXIBLE(obj) PyTypeNum_ISFLEXIBLE(((PyArray_Descr*)(obj))->type_num)
+#define PyDataType_ISDATETIME(obj) PyTypeNum_ISDATETIME(((PyArray_Descr*)(obj))->type_num)
+#define PyDataType_ISUSERDEF(obj) PyTypeNum_ISUSERDEF(((PyArray_Descr*)(obj))->type_num)
+#define PyDataType_ISEXTENDED(obj) PyTypeNum_ISEXTENDED(((PyArray_Descr*)(obj))->type_num)
+#define PyDataType_ISOBJECT(obj) PyTypeNum_ISOBJECT(((PyArray_Descr*)(obj))->type_num)
+#define PyDataType_MAKEUNSIZED(dtype) ((dtype)->elsize = 0)
+/*
+ * PyDataType_* FLAGS, FLACHK, REFCHK, HASFIELDS, HASSUBARRAY, UNSIZED,
+ * SUBARRAY, NAMES, FIELDS, C_METADATA, and METADATA require version specific
+ * lookup and are defined inĀ npy_2_compat.h.
+ */
+
+
+#define PyArray_ISBOOL(obj) PyTypeNum_ISBOOL(PyArray_TYPE(obj))
+#define PyArray_ISUNSIGNED(obj) PyTypeNum_ISUNSIGNED(PyArray_TYPE(obj))
+#define PyArray_ISSIGNED(obj) PyTypeNum_ISSIGNED(PyArray_TYPE(obj))
+#define PyArray_ISINTEGER(obj) PyTypeNum_ISINTEGER(PyArray_TYPE(obj))
+#define PyArray_ISFLOAT(obj) PyTypeNum_ISFLOAT(PyArray_TYPE(obj))
+#define PyArray_ISNUMBER(obj) PyTypeNum_ISNUMBER(PyArray_TYPE(obj))
+#define PyArray_ISSTRING(obj) PyTypeNum_ISSTRING(PyArray_TYPE(obj))
+#define PyArray_ISCOMPLEX(obj) PyTypeNum_ISCOMPLEX(PyArray_TYPE(obj))
+#define PyArray_ISFLEXIBLE(obj) PyTypeNum_ISFLEXIBLE(PyArray_TYPE(obj))
+#define PyArray_ISDATETIME(obj) PyTypeNum_ISDATETIME(PyArray_TYPE(obj))
+#define PyArray_ISUSERDEF(obj) PyTypeNum_ISUSERDEF(PyArray_TYPE(obj))
+#define PyArray_ISEXTENDED(obj) PyTypeNum_ISEXTENDED(PyArray_TYPE(obj))
+#define PyArray_ISOBJECT(obj) PyTypeNum_ISOBJECT(PyArray_TYPE(obj))
+#define PyArray_HASFIELDS(obj) PyDataType_HASFIELDS(PyArray_DESCR(obj))
+
+ /*
+ * FIXME: This should check for a flag on the data-type that
+ * states whether or not it is variable length. Because the
+ * ISFLEXIBLE check is hard-coded to the built-in data-types.
+ */
+#define PyArray_ISVARIABLE(obj) PyTypeNum_ISFLEXIBLE(PyArray_TYPE(obj))
+
+#define PyArray_SAFEALIGNEDCOPY(obj) (PyArray_ISALIGNED(obj) && !PyArray_ISVARIABLE(obj))
+
+
+#define NPY_LITTLE '<'
+#define NPY_BIG '>'
+#define NPY_NATIVE '='
+#define NPY_SWAP 's'
+#define NPY_IGNORE '|'
+
+#if NPY_BYTE_ORDER == NPY_BIG_ENDIAN
+#define NPY_NATBYTE NPY_BIG
+#define NPY_OPPBYTE NPY_LITTLE
+#else
+#define NPY_NATBYTE NPY_LITTLE
+#define NPY_OPPBYTE NPY_BIG
+#endif
+
+#define PyArray_ISNBO(arg) ((arg) != NPY_OPPBYTE)
+#define PyArray_IsNativeByteOrder PyArray_ISNBO
+#define PyArray_ISNOTSWAPPED(m) PyArray_ISNBO(PyArray_DESCR(m)->byteorder)
+#define PyArray_ISBYTESWAPPED(m) (!PyArray_ISNOTSWAPPED(m))
+
+#define PyArray_FLAGSWAP(m, flags) (PyArray_CHKFLAGS(m, flags) && \
+ PyArray_ISNOTSWAPPED(m))
+
+#define PyArray_ISCARRAY(m) PyArray_FLAGSWAP(m, NPY_ARRAY_CARRAY)
+#define PyArray_ISCARRAY_RO(m) PyArray_FLAGSWAP(m, NPY_ARRAY_CARRAY_RO)
+#define PyArray_ISFARRAY(m) PyArray_FLAGSWAP(m, NPY_ARRAY_FARRAY)
+#define PyArray_ISFARRAY_RO(m) PyArray_FLAGSWAP(m, NPY_ARRAY_FARRAY_RO)
+#define PyArray_ISBEHAVED(m) PyArray_FLAGSWAP(m, NPY_ARRAY_BEHAVED)
+#define PyArray_ISBEHAVED_RO(m) PyArray_FLAGSWAP(m, NPY_ARRAY_ALIGNED)
+
+
+#define PyDataType_ISNOTSWAPPED(d) PyArray_ISNBO(((PyArray_Descr *)(d))->byteorder)
+#define PyDataType_ISBYTESWAPPED(d) (!PyDataType_ISNOTSWAPPED(d))
+
+/************************************************************
+ * A struct used by PyArray_CreateSortedStridePerm, new in 1.7.
+ ************************************************************/
+
+typedef struct {
+ npy_intp perm, stride;
+} npy_stride_sort_item;
+
+/************************************************************
+ * This is the form of the struct that's stored in the
+ * PyCapsule returned by an array's __array_struct__ attribute. See
+ * https://docs.scipy.org/doc/numpy/reference/arrays.interface.html for the full
+ * documentation.
+ ************************************************************/
+typedef struct {
+ int two; /*
+ * contains the integer 2 as a sanity
+ * check
+ */
+
+ int nd; /* number of dimensions */
+
+ char typekind; /*
+ * kind in array --- character code of
+ * typestr
+ */
+
+ int itemsize; /* size of each element */
+
+ int flags; /*
+ * how should be data interpreted. Valid
+ * flags are CONTIGUOUS (1), F_CONTIGUOUS (2),
+ * ALIGNED (0x100), NOTSWAPPED (0x200), and
+ * WRITEABLE (0x400). ARR_HAS_DESCR (0x800)
+ * states that arrdescr field is present in
+ * structure
+ */
+
+ npy_intp *shape; /*
+ * A length-nd array of shape
+ * information
+ */
+
+ npy_intp *strides; /* A length-nd array of stride information */
+
+ void *data; /* A pointer to the first element of the array */
+
+ PyObject *descr; /*
+ * A list of fields or NULL (ignored if flags
+ * does not have ARR_HAS_DESCR flag set)
+ */
+} PyArrayInterface;
+
+
+/****************************************
+ * NpyString
+ *
+ * Types used by the NpyString API.
+ ****************************************/
+
+/*
+ * A "packed" encoded string. The string data must be accessed by first unpacking the string.
+ */
+typedef struct npy_packed_static_string npy_packed_static_string;
+
+/*
+ * An unpacked read-only view onto the data in a packed string
+ */
+typedef struct npy_unpacked_static_string {
+ size_t size;
+ const char *buf;
+} npy_static_string;
+
+/*
+ * Handles heap allocations for static strings.
+ */
+typedef struct npy_string_allocator npy_string_allocator;
+
+typedef struct {
+ PyArray_Descr base;
+ // The object representing a null value
+ PyObject *na_object;
+ // Flag indicating whether or not to coerce arbitrary objects to strings
+ char coerce;
+ // Flag indicating the na object is NaN-like
+ char has_nan_na;
+ // Flag indicating the na object is a string
+ char has_string_na;
+ // If nonzero, indicates that this instance is owned by an array already
+ char array_owned;
+ // The string data to use when a default string is needed
+ npy_static_string default_string;
+ // The name of the missing data object, if any
+ npy_static_string na_name;
+ // the allocator should only be directly accessed after
+ // acquiring the allocator_lock and the lock should
+ // be released immediately after the allocator is
+ // no longer needed
+ npy_string_allocator *allocator;
+} PyArray_StringDTypeObject;
+
+/*
+ * PyArray_DTypeMeta related definitions.
+ *
+ * As of now, this API is preliminary and will be extended as necessary.
+ */
+#if defined(NPY_INTERNAL_BUILD) && NPY_INTERNAL_BUILD
+ /*
+ * The Structures defined in this block are currently considered
+ * private API and may change without warning!
+ * Part of this (at least the size) is expected to be public API without
+ * further modifications.
+ */
+ /* TODO: Make this definition public in the API, as soon as its settled */
+ NPY_NO_EXPORT extern PyTypeObject PyArrayDTypeMeta_Type;
+
+ /*
+ * While NumPy DTypes would not need to be heap types the plan is to
+ * make DTypes available in Python at which point they will be heap types.
+ * Since we also wish to add fields to the DType class, this looks like
+ * a typical instance definition, but with PyHeapTypeObject instead of
+ * only the PyObject_HEAD.
+ * This must only be exposed very extremely careful consideration, since
+ * it is a fairly complex construct which may be better to allow
+ * refactoring of.
+ */
+ typedef struct {
+ PyHeapTypeObject super;
+
+ /*
+ * Most DTypes will have a singleton default instance, for the
+ * parametric legacy DTypes (bytes, string, void, datetime) this
+ * may be a pointer to the *prototype* instance?
+ */
+ PyArray_Descr *singleton;
+ /* Copy of the legacy DTypes type number, usually invalid. */
+ int type_num;
+
+ /* The type object of the scalar instances (may be NULL?) */
+ PyTypeObject *scalar_type;
+ /*
+ * DType flags to signal legacy, parametric, or
+ * abstract. But plenty of space for additional information/flags.
+ */
+ npy_uint64 flags;
+
+ /*
+ * Use indirection in order to allow a fixed size for this struct.
+ * A stable ABI size makes creating a static DType less painful
+ * while also ensuring flexibility for all opaque API (with one
+ * indirection due the pointer lookup).
+ */
+ void *dt_slots;
+ void *reserved[3];
+ } PyArray_DTypeMeta;
+
+#endif /* NPY_INTERNAL_BUILD */
+
+
+/*
+ * Use the keyword NPY_DEPRECATED_INCLUDES to ensure that the header files
+ * npy_*_*_deprecated_api.h are only included from here and nowhere else.
+ */
+#ifdef NPY_DEPRECATED_INCLUDES
+#error "Do not use the reserved keyword NPY_DEPRECATED_INCLUDES."
+#endif
+#define NPY_DEPRECATED_INCLUDES
+#if !defined(NPY_NO_DEPRECATED_API) || \
+ (NPY_NO_DEPRECATED_API < NPY_1_7_API_VERSION)
+#include "npy_1_7_deprecated_api.h"
+#endif
+/*
+ * There is no file npy_1_8_deprecated_api.h since there are no additional
+ * deprecated API features in NumPy 1.8.
+ *
+ * Note to maintainers: insert code like the following in future NumPy
+ * versions.
+ *
+ * #if !defined(NPY_NO_DEPRECATED_API) || \
+ * (NPY_NO_DEPRECATED_API < NPY_1_9_API_VERSION)
+ * #include "npy_1_9_deprecated_api.h"
+ * #endif
+ */
+#undef NPY_DEPRECATED_INCLUDES
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* NUMPY_CORE_INCLUDE_NUMPY_NDARRAYTYPES_H_ */
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/npy_1_7_deprecated_api.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/npy_1_7_deprecated_api.h
new file mode 100644
index 0000000000000000000000000000000000000000..be53cded488dd373072ab798fd7c25a5041e20ad
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/npy_1_7_deprecated_api.h
@@ -0,0 +1,112 @@
+#ifndef NPY_DEPRECATED_INCLUDES
+#error "Should never include npy_*_*_deprecated_api directly."
+#endif
+
+#ifndef NUMPY_CORE_INCLUDE_NUMPY_NPY_1_7_DEPRECATED_API_H_
+#define NUMPY_CORE_INCLUDE_NUMPY_NPY_1_7_DEPRECATED_API_H_
+
+/* Emit a warning if the user did not specifically request the old API */
+#ifndef NPY_NO_DEPRECATED_API
+#if defined(_WIN32)
+#define _WARN___STR2__(x) #x
+#define _WARN___STR1__(x) _WARN___STR2__(x)
+#define _WARN___LOC__ __FILE__ "(" _WARN___STR1__(__LINE__) ") : Warning Msg: "
+#pragma message(_WARN___LOC__"Using deprecated NumPy API, disable it with " \
+ "#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION")
+#else
+#warning "Using deprecated NumPy API, disable it with " \
+ "#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION"
+#endif
+#endif
+
+/*
+ * This header exists to collect all dangerous/deprecated NumPy API
+ * as of NumPy 1.7.
+ *
+ * This is an attempt to remove bad API, the proliferation of macros,
+ * and namespace pollution currently produced by the NumPy headers.
+ */
+
+/* These array flags are deprecated as of NumPy 1.7 */
+#define NPY_CONTIGUOUS NPY_ARRAY_C_CONTIGUOUS
+#define NPY_FORTRAN NPY_ARRAY_F_CONTIGUOUS
+
+/*
+ * The consistent NPY_ARRAY_* names which don't pollute the NPY_*
+ * namespace were added in NumPy 1.7.
+ *
+ * These versions of the carray flags are deprecated, but
+ * probably should only be removed after two releases instead of one.
+ */
+#define NPY_C_CONTIGUOUS NPY_ARRAY_C_CONTIGUOUS
+#define NPY_F_CONTIGUOUS NPY_ARRAY_F_CONTIGUOUS
+#define NPY_OWNDATA NPY_ARRAY_OWNDATA
+#define NPY_FORCECAST NPY_ARRAY_FORCECAST
+#define NPY_ENSURECOPY NPY_ARRAY_ENSURECOPY
+#define NPY_ENSUREARRAY NPY_ARRAY_ENSUREARRAY
+#define NPY_ELEMENTSTRIDES NPY_ARRAY_ELEMENTSTRIDES
+#define NPY_ALIGNED NPY_ARRAY_ALIGNED
+#define NPY_NOTSWAPPED NPY_ARRAY_NOTSWAPPED
+#define NPY_WRITEABLE NPY_ARRAY_WRITEABLE
+#define NPY_BEHAVED NPY_ARRAY_BEHAVED
+#define NPY_BEHAVED_NS NPY_ARRAY_BEHAVED_NS
+#define NPY_CARRAY NPY_ARRAY_CARRAY
+#define NPY_CARRAY_RO NPY_ARRAY_CARRAY_RO
+#define NPY_FARRAY NPY_ARRAY_FARRAY
+#define NPY_FARRAY_RO NPY_ARRAY_FARRAY_RO
+#define NPY_DEFAULT NPY_ARRAY_DEFAULT
+#define NPY_IN_ARRAY NPY_ARRAY_IN_ARRAY
+#define NPY_OUT_ARRAY NPY_ARRAY_OUT_ARRAY
+#define NPY_INOUT_ARRAY NPY_ARRAY_INOUT_ARRAY
+#define NPY_IN_FARRAY NPY_ARRAY_IN_FARRAY
+#define NPY_OUT_FARRAY NPY_ARRAY_OUT_FARRAY
+#define NPY_INOUT_FARRAY NPY_ARRAY_INOUT_FARRAY
+#define NPY_UPDATE_ALL NPY_ARRAY_UPDATE_ALL
+
+/* This way of accessing the default type is deprecated as of NumPy 1.7 */
+#define PyArray_DEFAULT NPY_DEFAULT_TYPE
+
+/*
+ * Deprecated as of NumPy 1.7, this kind of shortcut doesn't
+ * belong in the public API.
+ */
+#define NPY_AO PyArrayObject
+
+/*
+ * Deprecated as of NumPy 1.7, an all-lowercase macro doesn't
+ * belong in the public API.
+ */
+#define fortran fortran_
+
+/*
+ * Deprecated as of NumPy 1.7, as it is a namespace-polluting
+ * macro.
+ */
+#define FORTRAN_IF PyArray_FORTRAN_IF
+
+/* Deprecated as of NumPy 1.7, datetime64 uses c_metadata instead */
+#define NPY_METADATA_DTSTR "__timeunit__"
+
+/*
+ * Deprecated as of NumPy 1.7.
+ * The reasoning:
+ * - These are for datetime, but there's no datetime "namespace".
+ * - They just turn NPY_STR_ into "", which is just
+ * making something simple be indirected.
+ */
+#define NPY_STR_Y "Y"
+#define NPY_STR_M "M"
+#define NPY_STR_W "W"
+#define NPY_STR_D "D"
+#define NPY_STR_h "h"
+#define NPY_STR_m "m"
+#define NPY_STR_s "s"
+#define NPY_STR_ms "ms"
+#define NPY_STR_us "us"
+#define NPY_STR_ns "ns"
+#define NPY_STR_ps "ps"
+#define NPY_STR_fs "fs"
+#define NPY_STR_as "as"
+
+
+#endif /* NUMPY_CORE_INCLUDE_NUMPY_NPY_1_7_DEPRECATED_API_H_ */
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/npy_2_compat.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/npy_2_compat.h
new file mode 100644
index 0000000000000000000000000000000000000000..e39e65aedea7dc95a1130ea94518bb778d1238cd
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/npy_2_compat.h
@@ -0,0 +1,249 @@
+/*
+ * This header file defines relevant features which:
+ * - Require runtime inspection depending on the NumPy version.
+ * - May be needed when compiling with an older version of NumPy to allow
+ * a smooth transition.
+ *
+ * As such, it is shipped with NumPy 2.0, but designed to be vendored in full
+ * or parts by downstream projects.
+ *
+ * It must be included after any other includes. `import_array()` must have
+ * been called in the scope or version dependency will misbehave, even when
+ * only `PyUFunc_` API is used.
+ *
+ * If required complicated defs (with inline functions) should be written as:
+ *
+ * #if NPY_FEATURE_VERSION >= NPY_2_0_API_VERSION
+ * Simple definition when NumPy 2.0 API is guaranteed.
+ * #else
+ * static inline definition of a 1.x compatibility shim
+ * #if NPY_ABI_VERSION < 0x02000000
+ * Make 1.x compatibility shim the public API (1.x only branch)
+ * #else
+ * Runtime dispatched version (1.x or 2.x)
+ * #endif
+ * #endif
+ *
+ * An internal build always passes NPY_FEATURE_VERSION >= NPY_2_0_API_VERSION
+ */
+
+#ifndef NUMPY_CORE_INCLUDE_NUMPY_NPY_2_COMPAT_H_
+#define NUMPY_CORE_INCLUDE_NUMPY_NPY_2_COMPAT_H_
+
+/*
+ * New macros for accessing real and complex part of a complex number can be
+ * found in "npy_2_complexcompat.h".
+ */
+
+
+/*
+ * This header is meant to be included by downstream directly for 1.x compat.
+ * In that case we need to ensure that users first included the full headers
+ * and not just `ndarraytypes.h`.
+ */
+
+#ifndef NPY_FEATURE_VERSION
+ #error "The NumPy 2 compat header requires `import_array()` for which " \
+ "the `ndarraytypes.h` header include is not sufficient. Please " \
+ "include it after `numpy/ndarrayobject.h` or similar.\n" \
+ "To simplify inclusion, you may use `PyArray_ImportNumPy()` " \
+ "which is defined in the compat header and is lightweight (can be)."
+#endif
+
+#if NPY_ABI_VERSION < 0x02000000
+ /*
+ * Define 2.0 feature version as it is needed below to decide whether we
+ * compile for both 1.x and 2.x (defining it guarantees 1.x only).
+ */
+ #define NPY_2_0_API_VERSION 0x00000012
+ /*
+ * If we are compiling with NumPy 1.x, PyArray_RUNTIME_VERSION so we
+ * pretend the `PyArray_RUNTIME_VERSION` is `NPY_FEATURE_VERSION`.
+ * This allows downstream to use `PyArray_RUNTIME_VERSION` if they need to.
+ */
+ #define PyArray_RUNTIME_VERSION NPY_FEATURE_VERSION
+ /* Compiling on NumPy 1.x where these are the same: */
+ #define PyArray_DescrProto PyArray_Descr
+#endif
+
+
+/*
+ * Define a better way to call `_import_array()` to simplify backporting as
+ * we now require imports more often (necessary to make ABI flexible).
+ */
+#ifdef import_array1
+
+static inline int
+PyArray_ImportNumPyAPI(void)
+{
+ if (NPY_UNLIKELY(PyArray_API == NULL)) {
+ import_array1(-1);
+ }
+ return 0;
+}
+
+#endif /* import_array1 */
+
+
+/*
+ * NPY_DEFAULT_INT
+ *
+ * The default integer has changed, `NPY_DEFAULT_INT` is available at runtime
+ * for use as type number, e.g. `PyArray_DescrFromType(NPY_DEFAULT_INT)`.
+ *
+ * NPY_RAVEL_AXIS
+ *
+ * This was introduced in NumPy 2.0 to allow indicating that an axis should be
+ * raveled in an operation. Before NumPy 2.0, NPY_MAXDIMS was used for this purpose.
+ *
+ * NPY_MAXDIMS
+ *
+ * A constant indicating the maximum number dimensions allowed when creating
+ * an ndarray.
+ *
+ * NPY_NTYPES_LEGACY
+ *
+ * The number of built-in NumPy dtypes.
+ */
+#if NPY_FEATURE_VERSION >= NPY_2_0_API_VERSION
+ #define NPY_DEFAULT_INT NPY_INTP
+ #define NPY_RAVEL_AXIS NPY_MIN_INT
+ #define NPY_MAXARGS 64
+
+#elif NPY_ABI_VERSION < 0x02000000
+ #define NPY_DEFAULT_INT NPY_LONG
+ #define NPY_RAVEL_AXIS 32
+ #define NPY_MAXARGS 32
+
+ /* Aliases of 2.x names to 1.x only equivalent names */
+ #define NPY_NTYPES NPY_NTYPES_LEGACY
+ #define PyArray_DescrProto PyArray_Descr
+ #define _PyArray_LegacyDescr PyArray_Descr
+ /* NumPy 2 definition always works, but add it for 1.x only */
+ #define PyDataType_ISLEGACY(dtype) (1)
+#else
+ #define NPY_DEFAULT_INT \
+ (PyArray_RUNTIME_VERSION >= NPY_2_0_API_VERSION ? NPY_INTP : NPY_LONG)
+ #define NPY_RAVEL_AXIS \
+ (PyArray_RUNTIME_VERSION >= NPY_2_0_API_VERSION ? NPY_MIN_INT : 32)
+ #define NPY_MAXARGS \
+ (PyArray_RUNTIME_VERSION >= NPY_2_0_API_VERSION ? 64 : 32)
+#endif
+
+
+/*
+ * Access inline functions for descriptor fields. Except for the first
+ * few fields, these needed to be moved (elsize, alignment) for
+ * additional space. Or they are descriptor specific and are not generally
+ * available anymore (metadata, c_metadata, subarray, names, fields).
+ *
+ * Most of these are defined via the `DESCR_ACCESSOR` macro helper.
+ */
+#if NPY_FEATURE_VERSION >= NPY_2_0_API_VERSION || NPY_ABI_VERSION < 0x02000000
+ /* Compiling for 1.x or 2.x only, direct field access is OK: */
+
+ static inline void
+ PyDataType_SET_ELSIZE(PyArray_Descr *dtype, npy_intp size)
+ {
+ dtype->elsize = size;
+ }
+
+ static inline npy_uint64
+ PyDataType_FLAGS(const PyArray_Descr *dtype)
+ {
+ #if NPY_FEATURE_VERSION >= NPY_2_0_API_VERSION
+ return dtype->flags;
+ #else
+ return (unsigned char)dtype->flags; /* Need unsigned cast on 1.x */
+ #endif
+ }
+
+ #define DESCR_ACCESSOR(FIELD, field, type, legacy_only) \
+ static inline type \
+ PyDataType_##FIELD(const PyArray_Descr *dtype) { \
+ if (legacy_only && !PyDataType_ISLEGACY(dtype)) { \
+ return (type)0; \
+ } \
+ return ((_PyArray_LegacyDescr *)dtype)->field; \
+ }
+#else /* compiling for both 1.x and 2.x */
+
+ static inline void
+ PyDataType_SET_ELSIZE(PyArray_Descr *dtype, npy_intp size)
+ {
+ if (PyArray_RUNTIME_VERSION >= NPY_2_0_API_VERSION) {
+ ((_PyArray_DescrNumPy2 *)dtype)->elsize = size;
+ }
+ else {
+ ((PyArray_DescrProto *)dtype)->elsize = (int)size;
+ }
+ }
+
+ static inline npy_uint64
+ PyDataType_FLAGS(const PyArray_Descr *dtype)
+ {
+ if (PyArray_RUNTIME_VERSION >= NPY_2_0_API_VERSION) {
+ return ((_PyArray_DescrNumPy2 *)dtype)->flags;
+ }
+ else {
+ return (unsigned char)((PyArray_DescrProto *)dtype)->flags;
+ }
+ }
+
+ /* Cast to LegacyDescr always fine but needed when `legacy_only` */
+ #define DESCR_ACCESSOR(FIELD, field, type, legacy_only) \
+ static inline type \
+ PyDataType_##FIELD(const PyArray_Descr *dtype) { \
+ if (legacy_only && !PyDataType_ISLEGACY(dtype)) { \
+ return (type)0; \
+ } \
+ if (PyArray_RUNTIME_VERSION >= NPY_2_0_API_VERSION) { \
+ return ((_PyArray_LegacyDescr *)dtype)->field; \
+ } \
+ else { \
+ return ((PyArray_DescrProto *)dtype)->field; \
+ } \
+ }
+#endif
+
+DESCR_ACCESSOR(ELSIZE, elsize, npy_intp, 0)
+DESCR_ACCESSOR(ALIGNMENT, alignment, npy_intp, 0)
+DESCR_ACCESSOR(METADATA, metadata, PyObject *, 1)
+DESCR_ACCESSOR(SUBARRAY, subarray, PyArray_ArrayDescr *, 1)
+DESCR_ACCESSOR(NAMES, names, PyObject *, 1)
+DESCR_ACCESSOR(FIELDS, fields, PyObject *, 1)
+DESCR_ACCESSOR(C_METADATA, c_metadata, NpyAuxData *, 1)
+
+#undef DESCR_ACCESSOR
+
+
+#if !(defined(NPY_INTERNAL_BUILD) && NPY_INTERNAL_BUILD)
+#if NPY_FEATURE_VERSION >= NPY_2_0_API_VERSION
+ static inline PyArray_ArrFuncs *
+ PyDataType_GetArrFuncs(const PyArray_Descr *descr)
+ {
+ return _PyDataType_GetArrFuncs(descr);
+ }
+#elif NPY_ABI_VERSION < 0x02000000
+ static inline PyArray_ArrFuncs *
+ PyDataType_GetArrFuncs(const PyArray_Descr *descr)
+ {
+ return descr->f;
+ }
+#else
+ static inline PyArray_ArrFuncs *
+ PyDataType_GetArrFuncs(const PyArray_Descr *descr)
+ {
+ if (PyArray_RUNTIME_VERSION >= NPY_2_0_API_VERSION) {
+ return _PyDataType_GetArrFuncs(descr);
+ }
+ else {
+ return ((PyArray_DescrProto *)descr)->f;
+ }
+ }
+#endif
+
+
+#endif /* not internal build */
+
+#endif /* NUMPY_CORE_INCLUDE_NUMPY_NPY_2_COMPAT_H_ */
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/npy_2_complexcompat.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/npy_2_complexcompat.h
new file mode 100644
index 0000000000000000000000000000000000000000..0b509011b2803b978bd913191816a9bbd6635d35
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/npy_2_complexcompat.h
@@ -0,0 +1,28 @@
+/* This header is designed to be copy-pasted into downstream packages, since it provides
+ a compatibility layer between the old C struct complex types and the new native C99
+ complex types. The new macros are in numpy/npy_math.h, which is why it is included here. */
+#ifndef NUMPY_CORE_INCLUDE_NUMPY_NPY_2_COMPLEXCOMPAT_H_
+#define NUMPY_CORE_INCLUDE_NUMPY_NPY_2_COMPLEXCOMPAT_H_
+
+#include
+
+#ifndef NPY_CSETREALF
+#define NPY_CSETREALF(c, r) (c)->real = (r)
+#endif
+#ifndef NPY_CSETIMAGF
+#define NPY_CSETIMAGF(c, i) (c)->imag = (i)
+#endif
+#ifndef NPY_CSETREAL
+#define NPY_CSETREAL(c, r) (c)->real = (r)
+#endif
+#ifndef NPY_CSETIMAG
+#define NPY_CSETIMAG(c, i) (c)->imag = (i)
+#endif
+#ifndef NPY_CSETREALL
+#define NPY_CSETREALL(c, r) (c)->real = (r)
+#endif
+#ifndef NPY_CSETIMAGL
+#define NPY_CSETIMAGL(c, i) (c)->imag = (i)
+#endif
+
+#endif
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/npy_3kcompat.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/npy_3kcompat.h
new file mode 100644
index 0000000000000000000000000000000000000000..c2bf74faf09d9df0df07f23e7d8b8550fe79ba5f
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/npy_3kcompat.h
@@ -0,0 +1,374 @@
+/*
+ * This is a convenience header file providing compatibility utilities
+ * for supporting different minor versions of Python 3.
+ * It was originally used to support the transition from Python 2,
+ * hence the "3k" naming.
+ *
+ * If you want to use this for your own projects, it's recommended to make a
+ * copy of it. We don't provide backwards compatibility guarantees.
+ */
+
+#ifndef NUMPY_CORE_INCLUDE_NUMPY_NPY_3KCOMPAT_H_
+#define NUMPY_CORE_INCLUDE_NUMPY_NPY_3KCOMPAT_H_
+
+#include
+#include
+
+#include "npy_common.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Python13 removes _PyLong_AsInt */
+static inline int
+Npy__PyLong_AsInt(PyObject *obj)
+{
+ int overflow;
+ long result = PyLong_AsLongAndOverflow(obj, &overflow);
+
+ /* INT_MAX and INT_MIN are defined in Python.h */
+ if (overflow || result > INT_MAX || result < INT_MIN) {
+ /* XXX: could be cute and give a different
+ message for overflow == -1 */
+ PyErr_SetString(PyExc_OverflowError,
+ "Python int too large to convert to C int");
+ return -1;
+ }
+ return (int)result;
+}
+
+#if defined _MSC_VER && _MSC_VER >= 1900
+
+#include
+
+/*
+ * Macros to protect CRT calls against instant termination when passed an
+ * invalid parameter (https://bugs.python.org/issue23524).
+ */
+extern _invalid_parameter_handler _Py_silent_invalid_parameter_handler;
+#define NPY_BEGIN_SUPPRESS_IPH { _invalid_parameter_handler _Py_old_handler = \
+ _set_thread_local_invalid_parameter_handler(_Py_silent_invalid_parameter_handler);
+#define NPY_END_SUPPRESS_IPH _set_thread_local_invalid_parameter_handler(_Py_old_handler); }
+
+#else
+
+#define NPY_BEGIN_SUPPRESS_IPH
+#define NPY_END_SUPPRESS_IPH
+
+#endif /* _MSC_VER >= 1900 */
+
+/*
+ * PyFile_* compatibility
+ */
+
+/*
+ * Get a FILE* handle to the file represented by the Python object
+ */
+static inline FILE*
+npy_PyFile_Dup2(PyObject *file, char *mode, npy_off_t *orig_pos)
+{
+ int fd, fd2, unbuf;
+ Py_ssize_t fd2_tmp;
+ PyObject *ret, *os, *io, *io_raw;
+ npy_off_t pos;
+ FILE *handle;
+
+ /* Flush first to ensure things end up in the file in the correct order */
+ ret = PyObject_CallMethod(file, "flush", "");
+ if (ret == NULL) {
+ return NULL;
+ }
+ Py_DECREF(ret);
+ fd = PyObject_AsFileDescriptor(file);
+ if (fd == -1) {
+ return NULL;
+ }
+
+ /*
+ * The handle needs to be dup'd because we have to call fclose
+ * at the end
+ */
+ os = PyImport_ImportModule("os");
+ if (os == NULL) {
+ return NULL;
+ }
+ ret = PyObject_CallMethod(os, "dup", "i", fd);
+ Py_DECREF(os);
+ if (ret == NULL) {
+ return NULL;
+ }
+ fd2_tmp = PyNumber_AsSsize_t(ret, PyExc_IOError);
+ Py_DECREF(ret);
+ if (fd2_tmp == -1 && PyErr_Occurred()) {
+ return NULL;
+ }
+ if (fd2_tmp < INT_MIN || fd2_tmp > INT_MAX) {
+ PyErr_SetString(PyExc_IOError,
+ "Getting an 'int' from os.dup() failed");
+ return NULL;
+ }
+ fd2 = (int)fd2_tmp;
+
+ /* Convert to FILE* handle */
+#ifdef _WIN32
+ NPY_BEGIN_SUPPRESS_IPH
+ handle = _fdopen(fd2, mode);
+ NPY_END_SUPPRESS_IPH
+#else
+ handle = fdopen(fd2, mode);
+#endif
+ if (handle == NULL) {
+ PyErr_SetString(PyExc_IOError,
+ "Getting a FILE* from a Python file object via "
+ "_fdopen failed. If you built NumPy, you probably "
+ "linked with the wrong debug/release runtime");
+ return NULL;
+ }
+
+ /* Record the original raw file handle position */
+ *orig_pos = npy_ftell(handle);
+ if (*orig_pos == -1) {
+ /* The io module is needed to determine if buffering is used */
+ io = PyImport_ImportModule("io");
+ if (io == NULL) {
+ fclose(handle);
+ return NULL;
+ }
+ /* File object instances of RawIOBase are unbuffered */
+ io_raw = PyObject_GetAttrString(io, "RawIOBase");
+ Py_DECREF(io);
+ if (io_raw == NULL) {
+ fclose(handle);
+ return NULL;
+ }
+ unbuf = PyObject_IsInstance(file, io_raw);
+ Py_DECREF(io_raw);
+ if (unbuf == 1) {
+ /* Succeed if the IO is unbuffered */
+ return handle;
+ }
+ else {
+ PyErr_SetString(PyExc_IOError, "obtaining file position failed");
+ fclose(handle);
+ return NULL;
+ }
+ }
+
+ /* Seek raw handle to the Python-side position */
+ ret = PyObject_CallMethod(file, "tell", "");
+ if (ret == NULL) {
+ fclose(handle);
+ return NULL;
+ }
+ pos = PyLong_AsLongLong(ret);
+ Py_DECREF(ret);
+ if (PyErr_Occurred()) {
+ fclose(handle);
+ return NULL;
+ }
+ if (npy_fseek(handle, pos, SEEK_SET) == -1) {
+ PyErr_SetString(PyExc_IOError, "seeking file failed");
+ fclose(handle);
+ return NULL;
+ }
+ return handle;
+}
+
+/*
+ * Close the dup-ed file handle, and seek the Python one to the current position
+ */
+static inline int
+npy_PyFile_DupClose2(PyObject *file, FILE* handle, npy_off_t orig_pos)
+{
+ int fd, unbuf;
+ PyObject *ret, *io, *io_raw;
+ npy_off_t position;
+
+ position = npy_ftell(handle);
+
+ /* Close the FILE* handle */
+ fclose(handle);
+
+ /*
+ * Restore original file handle position, in order to not confuse
+ * Python-side data structures
+ */
+ fd = PyObject_AsFileDescriptor(file);
+ if (fd == -1) {
+ return -1;
+ }
+
+ if (npy_lseek(fd, orig_pos, SEEK_SET) == -1) {
+
+ /* The io module is needed to determine if buffering is used */
+ io = PyImport_ImportModule("io");
+ if (io == NULL) {
+ return -1;
+ }
+ /* File object instances of RawIOBase are unbuffered */
+ io_raw = PyObject_GetAttrString(io, "RawIOBase");
+ Py_DECREF(io);
+ if (io_raw == NULL) {
+ return -1;
+ }
+ unbuf = PyObject_IsInstance(file, io_raw);
+ Py_DECREF(io_raw);
+ if (unbuf == 1) {
+ /* Succeed if the IO is unbuffered */
+ return 0;
+ }
+ else {
+ PyErr_SetString(PyExc_IOError, "seeking file failed");
+ return -1;
+ }
+ }
+
+ if (position == -1) {
+ PyErr_SetString(PyExc_IOError, "obtaining file position failed");
+ return -1;
+ }
+
+ /* Seek Python-side handle to the FILE* handle position */
+ ret = PyObject_CallMethod(file, "seek", NPY_OFF_T_PYFMT "i", position, 0);
+ if (ret == NULL) {
+ return -1;
+ }
+ Py_DECREF(ret);
+ return 0;
+}
+
+static inline PyObject*
+npy_PyFile_OpenFile(PyObject *filename, const char *mode)
+{
+ PyObject *open;
+ open = PyDict_GetItemString(PyEval_GetBuiltins(), "open");
+ if (open == NULL) {
+ return NULL;
+ }
+ return PyObject_CallFunction(open, "Os", filename, mode);
+}
+
+static inline int
+npy_PyFile_CloseFile(PyObject *file)
+{
+ PyObject *ret;
+
+ ret = PyObject_CallMethod(file, "close", NULL);
+ if (ret == NULL) {
+ return -1;
+ }
+ Py_DECREF(ret);
+ return 0;
+}
+
+/* This is a copy of _PyErr_ChainExceptions, which
+ * is no longer exported from Python3.12
+ */
+static inline void
+npy_PyErr_ChainExceptions(PyObject *exc, PyObject *val, PyObject *tb)
+{
+ if (exc == NULL)
+ return;
+
+ if (PyErr_Occurred()) {
+ PyObject *exc2, *val2, *tb2;
+ PyErr_Fetch(&exc2, &val2, &tb2);
+ PyErr_NormalizeException(&exc, &val, &tb);
+ if (tb != NULL) {
+ PyException_SetTraceback(val, tb);
+ Py_DECREF(tb);
+ }
+ Py_DECREF(exc);
+ PyErr_NormalizeException(&exc2, &val2, &tb2);
+ PyException_SetContext(val2, val);
+ PyErr_Restore(exc2, val2, tb2);
+ }
+ else {
+ PyErr_Restore(exc, val, tb);
+ }
+}
+
+/* This is a copy of _PyErr_ChainExceptions, with:
+ * __cause__ used instead of __context__
+ */
+static inline void
+npy_PyErr_ChainExceptionsCause(PyObject *exc, PyObject *val, PyObject *tb)
+{
+ if (exc == NULL)
+ return;
+
+ if (PyErr_Occurred()) {
+ PyObject *exc2, *val2, *tb2;
+ PyErr_Fetch(&exc2, &val2, &tb2);
+ PyErr_NormalizeException(&exc, &val, &tb);
+ if (tb != NULL) {
+ PyException_SetTraceback(val, tb);
+ Py_DECREF(tb);
+ }
+ Py_DECREF(exc);
+ PyErr_NormalizeException(&exc2, &val2, &tb2);
+ PyException_SetCause(val2, val);
+ PyErr_Restore(exc2, val2, tb2);
+ }
+ else {
+ PyErr_Restore(exc, val, tb);
+ }
+}
+
+/*
+ * PyCObject functions adapted to PyCapsules.
+ *
+ * The main job here is to get rid of the improved error handling
+ * of PyCapsules. It's a shame...
+ */
+static inline PyObject *
+NpyCapsule_FromVoidPtr(void *ptr, void (*dtor)(PyObject *))
+{
+ PyObject *ret = PyCapsule_New(ptr, NULL, dtor);
+ if (ret == NULL) {
+ PyErr_Clear();
+ }
+ return ret;
+}
+
+static inline PyObject *
+NpyCapsule_FromVoidPtrAndDesc(void *ptr, void* context, void (*dtor)(PyObject *))
+{
+ PyObject *ret = NpyCapsule_FromVoidPtr(ptr, dtor);
+ if (ret != NULL && PyCapsule_SetContext(ret, context) != 0) {
+ PyErr_Clear();
+ Py_DECREF(ret);
+ ret = NULL;
+ }
+ return ret;
+}
+
+static inline void *
+NpyCapsule_AsVoidPtr(PyObject *obj)
+{
+ void *ret = PyCapsule_GetPointer(obj, NULL);
+ if (ret == NULL) {
+ PyErr_Clear();
+ }
+ return ret;
+}
+
+static inline void *
+NpyCapsule_GetDesc(PyObject *obj)
+{
+ return PyCapsule_GetContext(obj);
+}
+
+static inline int
+NpyCapsule_Check(PyObject *ptr)
+{
+ return PyCapsule_CheckExact(ptr);
+}
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif /* NUMPY_CORE_INCLUDE_NUMPY_NPY_3KCOMPAT_H_ */
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/npy_common.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/npy_common.h
new file mode 100644
index 0000000000000000000000000000000000000000..79ad8ad78cb2bc68867b3002b091e5d7e7b6bc9a
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/npy_common.h
@@ -0,0 +1,1070 @@
+#ifndef NUMPY_CORE_INCLUDE_NUMPY_NPY_COMMON_H_
+#define NUMPY_CORE_INCLUDE_NUMPY_NPY_COMMON_H_
+
+/* need Python.h for npy_intp, npy_uintp */
+#include
+
+/* numpconfig.h is auto-generated */
+#include "numpyconfig.h"
+#ifdef HAVE_NPY_CONFIG_H
+#include
+#endif
+
+/*
+ * using static inline modifiers when defining npy_math functions
+ * allows the compiler to make optimizations when possible
+ */
+#ifndef NPY_INLINE_MATH
+#if defined(NPY_INTERNAL_BUILD) && NPY_INTERNAL_BUILD
+ #define NPY_INLINE_MATH 1
+#else
+ #define NPY_INLINE_MATH 0
+#endif
+#endif
+
+/*
+ * gcc does not unroll even with -O3
+ * use with care, unrolling on modern cpus rarely speeds things up
+ */
+#ifdef HAVE_ATTRIBUTE_OPTIMIZE_UNROLL_LOOPS
+#define NPY_GCC_UNROLL_LOOPS \
+ __attribute__((optimize("unroll-loops")))
+#else
+#define NPY_GCC_UNROLL_LOOPS
+#endif
+
+/* highest gcc optimization level, enabled autovectorizer */
+#ifdef HAVE_ATTRIBUTE_OPTIMIZE_OPT_3
+#define NPY_GCC_OPT_3 __attribute__((optimize("O3")))
+#else
+#define NPY_GCC_OPT_3
+#endif
+
+/*
+ * mark an argument (starting from 1) that must not be NULL and is not checked
+ * DO NOT USE IF FUNCTION CHECKS FOR NULL!! the compiler will remove the check
+ */
+#ifdef HAVE_ATTRIBUTE_NONNULL
+#define NPY_GCC_NONNULL(n) __attribute__((nonnull(n)))
+#else
+#define NPY_GCC_NONNULL(n)
+#endif
+
+/*
+ * give a hint to the compiler which branch is more likely or unlikely
+ * to occur, e.g. rare error cases:
+ *
+ * if (NPY_UNLIKELY(failure == 0))
+ * return NULL;
+ *
+ * the double !! is to cast the expression (e.g. NULL) to a boolean required by
+ * the intrinsic
+ */
+#ifdef HAVE___BUILTIN_EXPECT
+#define NPY_LIKELY(x) __builtin_expect(!!(x), 1)
+#define NPY_UNLIKELY(x) __builtin_expect(!!(x), 0)
+#else
+#define NPY_LIKELY(x) (x)
+#define NPY_UNLIKELY(x) (x)
+#endif
+
+#ifdef HAVE___BUILTIN_PREFETCH
+/* unlike _mm_prefetch also works on non-x86 */
+#define NPY_PREFETCH(x, rw, loc) __builtin_prefetch((x), (rw), (loc))
+#else
+#ifdef NPY_HAVE_SSE
+/* _MM_HINT_ET[01] (rw = 1) unsupported, only available in gcc >= 4.9 */
+#define NPY_PREFETCH(x, rw, loc) _mm_prefetch((x), loc == 0 ? _MM_HINT_NTA : \
+ (loc == 1 ? _MM_HINT_T2 : \
+ (loc == 2 ? _MM_HINT_T1 : \
+ (loc == 3 ? _MM_HINT_T0 : -1))))
+#else
+#define NPY_PREFETCH(x, rw,loc)
+#endif
+#endif
+
+/* `NPY_INLINE` kept for backwards compatibility; use `inline` instead */
+#if defined(_MSC_VER) && !defined(__clang__)
+ #define NPY_INLINE __inline
+/* clang included here to handle clang-cl on Windows */
+#elif defined(__GNUC__) || defined(__clang__)
+ #if defined(__STRICT_ANSI__)
+ #define NPY_INLINE __inline__
+ #else
+ #define NPY_INLINE inline
+ #endif
+#else
+ #define NPY_INLINE
+#endif
+
+#ifdef _MSC_VER
+ #define NPY_FINLINE static __forceinline
+#elif defined(__GNUC__)
+ #define NPY_FINLINE static inline __attribute__((always_inline))
+#else
+ #define NPY_FINLINE static
+#endif
+
+#if defined(_MSC_VER)
+ #define NPY_NOINLINE static __declspec(noinline)
+#elif defined(__GNUC__) || defined(__clang__)
+ #define NPY_NOINLINE static __attribute__((noinline))
+#else
+ #define NPY_NOINLINE static
+#endif
+
+#ifdef __cplusplus
+ #define NPY_TLS thread_local
+#elif defined(HAVE_THREAD_LOCAL)
+ #define NPY_TLS thread_local
+#elif defined(HAVE__THREAD_LOCAL)
+ #define NPY_TLS _Thread_local
+#elif defined(HAVE___THREAD)
+ #define NPY_TLS __thread
+#elif defined(HAVE___DECLSPEC_THREAD_)
+ #define NPY_TLS __declspec(thread)
+#else
+ #define NPY_TLS
+#endif
+
+#ifdef WITH_CPYCHECKER_RETURNS_BORROWED_REF_ATTRIBUTE
+ #define NPY_RETURNS_BORROWED_REF \
+ __attribute__((cpychecker_returns_borrowed_ref))
+#else
+ #define NPY_RETURNS_BORROWED_REF
+#endif
+
+#ifdef WITH_CPYCHECKER_STEALS_REFERENCE_TO_ARG_ATTRIBUTE
+ #define NPY_STEALS_REF_TO_ARG(n) \
+ __attribute__((cpychecker_steals_reference_to_arg(n)))
+#else
+ #define NPY_STEALS_REF_TO_ARG(n)
+#endif
+
+/* 64 bit file position support, also on win-amd64. Issue gh-2256 */
+#if defined(_MSC_VER) && defined(_WIN64) && (_MSC_VER > 1400) || \
+ defined(__MINGW32__) || defined(__MINGW64__)
+ #include
+
+ #define npy_fseek _fseeki64
+ #define npy_ftell _ftelli64
+ #define npy_lseek _lseeki64
+ #define npy_off_t npy_int64
+
+ #if NPY_SIZEOF_INT == 8
+ #define NPY_OFF_T_PYFMT "i"
+ #elif NPY_SIZEOF_LONG == 8
+ #define NPY_OFF_T_PYFMT "l"
+ #elif NPY_SIZEOF_LONGLONG == 8
+ #define NPY_OFF_T_PYFMT "L"
+ #else
+ #error Unsupported size for type off_t
+ #endif
+#else
+#ifdef HAVE_FSEEKO
+ #define npy_fseek fseeko
+#else
+ #define npy_fseek fseek
+#endif
+#ifdef HAVE_FTELLO
+ #define npy_ftell ftello
+#else
+ #define npy_ftell ftell
+#endif
+ #include
+ #ifndef _WIN32
+ #include
+ #endif
+ #define npy_lseek lseek
+ #define npy_off_t off_t
+
+ #if NPY_SIZEOF_OFF_T == NPY_SIZEOF_SHORT
+ #define NPY_OFF_T_PYFMT "h"
+ #elif NPY_SIZEOF_OFF_T == NPY_SIZEOF_INT
+ #define NPY_OFF_T_PYFMT "i"
+ #elif NPY_SIZEOF_OFF_T == NPY_SIZEOF_LONG
+ #define NPY_OFF_T_PYFMT "l"
+ #elif NPY_SIZEOF_OFF_T == NPY_SIZEOF_LONGLONG
+ #define NPY_OFF_T_PYFMT "L"
+ #else
+ #error Unsupported size for type off_t
+ #endif
+#endif
+
+/* enums for detected endianness */
+enum {
+ NPY_CPU_UNKNOWN_ENDIAN,
+ NPY_CPU_LITTLE,
+ NPY_CPU_BIG
+};
+
+/*
+ * This is to typedef npy_intp to the appropriate size for Py_ssize_t.
+ * (Before NumPy 2.0 we used Py_intptr_t and Py_uintptr_t from `pyport.h`.)
+ */
+typedef Py_ssize_t npy_intp;
+typedef size_t npy_uintp;
+
+/*
+ * Define sizes that were not defined in numpyconfig.h.
+ */
+#define NPY_SIZEOF_CHAR 1
+#define NPY_SIZEOF_BYTE 1
+#define NPY_SIZEOF_DATETIME 8
+#define NPY_SIZEOF_TIMEDELTA 8
+#define NPY_SIZEOF_HALF 2
+#define NPY_SIZEOF_CFLOAT NPY_SIZEOF_COMPLEX_FLOAT
+#define NPY_SIZEOF_CDOUBLE NPY_SIZEOF_COMPLEX_DOUBLE
+#define NPY_SIZEOF_CLONGDOUBLE NPY_SIZEOF_COMPLEX_LONGDOUBLE
+
+#ifdef constchar
+#undef constchar
+#endif
+
+#define NPY_SSIZE_T_PYFMT "n"
+#define constchar char
+
+/* NPY_INTP_FMT Note:
+ * Unlike the other NPY_*_FMT macros, which are used with PyOS_snprintf,
+ * NPY_INTP_FMT is used with PyErr_Format and PyUnicode_FromFormat. Those
+ * functions use different formatting codes that are portably specified
+ * according to the Python documentation. See issue gh-2388.
+ */
+#if NPY_SIZEOF_INTP == NPY_SIZEOF_LONG
+ #define NPY_INTP NPY_LONG
+ #define NPY_UINTP NPY_ULONG
+ #define PyIntpArrType_Type PyLongArrType_Type
+ #define PyUIntpArrType_Type PyULongArrType_Type
+ #define NPY_MAX_INTP NPY_MAX_LONG
+ #define NPY_MIN_INTP NPY_MIN_LONG
+ #define NPY_MAX_UINTP NPY_MAX_ULONG
+ #define NPY_INTP_FMT "ld"
+#elif NPY_SIZEOF_INTP == NPY_SIZEOF_INT
+ #define NPY_INTP NPY_INT
+ #define NPY_UINTP NPY_UINT
+ #define PyIntpArrType_Type PyIntArrType_Type
+ #define PyUIntpArrType_Type PyUIntArrType_Type
+ #define NPY_MAX_INTP NPY_MAX_INT
+ #define NPY_MIN_INTP NPY_MIN_INT
+ #define NPY_MAX_UINTP NPY_MAX_UINT
+ #define NPY_INTP_FMT "d"
+#elif defined(PY_LONG_LONG) && (NPY_SIZEOF_INTP == NPY_SIZEOF_LONGLONG)
+ #define NPY_INTP NPY_LONGLONG
+ #define NPY_UINTP NPY_ULONGLONG
+ #define PyIntpArrType_Type PyLongLongArrType_Type
+ #define PyUIntpArrType_Type PyULongLongArrType_Type
+ #define NPY_MAX_INTP NPY_MAX_LONGLONG
+ #define NPY_MIN_INTP NPY_MIN_LONGLONG
+ #define NPY_MAX_UINTP NPY_MAX_ULONGLONG
+ #define NPY_INTP_FMT "lld"
+#else
+ #error "Failed to correctly define NPY_INTP and NPY_UINTP"
+#endif
+
+
+/*
+ * Some platforms don't define bool, long long, or long double.
+ * Handle that here.
+ */
+#define NPY_BYTE_FMT "hhd"
+#define NPY_UBYTE_FMT "hhu"
+#define NPY_SHORT_FMT "hd"
+#define NPY_USHORT_FMT "hu"
+#define NPY_INT_FMT "d"
+#define NPY_UINT_FMT "u"
+#define NPY_LONG_FMT "ld"
+#define NPY_ULONG_FMT "lu"
+#define NPY_HALF_FMT "g"
+#define NPY_FLOAT_FMT "g"
+#define NPY_DOUBLE_FMT "g"
+
+
+#ifdef PY_LONG_LONG
+typedef PY_LONG_LONG npy_longlong;
+typedef unsigned PY_LONG_LONG npy_ulonglong;
+# ifdef _MSC_VER
+# define NPY_LONGLONG_FMT "I64d"
+# define NPY_ULONGLONG_FMT "I64u"
+# else
+# define NPY_LONGLONG_FMT "lld"
+# define NPY_ULONGLONG_FMT "llu"
+# endif
+# ifdef _MSC_VER
+# define NPY_LONGLONG_SUFFIX(x) (x##i64)
+# define NPY_ULONGLONG_SUFFIX(x) (x##Ui64)
+# else
+# define NPY_LONGLONG_SUFFIX(x) (x##LL)
+# define NPY_ULONGLONG_SUFFIX(x) (x##ULL)
+# endif
+#else
+typedef long npy_longlong;
+typedef unsigned long npy_ulonglong;
+# define NPY_LONGLONG_SUFFIX(x) (x##L)
+# define NPY_ULONGLONG_SUFFIX(x) (x##UL)
+#endif
+
+
+typedef unsigned char npy_bool;
+#define NPY_FALSE 0
+#define NPY_TRUE 1
+/*
+ * `NPY_SIZEOF_LONGDOUBLE` isn't usually equal to sizeof(long double).
+ * In some certain cases, it may forced to be equal to sizeof(double)
+ * even against the compiler implementation and the same goes for
+ * `complex long double`.
+ *
+ * Therefore, avoid `long double`, use `npy_longdouble` instead,
+ * and when it comes to standard math functions make sure of using
+ * the double version when `NPY_SIZEOF_LONGDOUBLE` == `NPY_SIZEOF_DOUBLE`.
+ * For example:
+ * npy_longdouble *ptr, x;
+ * #if NPY_SIZEOF_LONGDOUBLE == NPY_SIZEOF_DOUBLE
+ * npy_longdouble r = modf(x, ptr);
+ * #else
+ * npy_longdouble r = modfl(x, ptr);
+ * #endif
+ *
+ * See https://github.com/numpy/numpy/issues/20348
+ */
+#if NPY_SIZEOF_LONGDOUBLE == NPY_SIZEOF_DOUBLE
+ #define NPY_LONGDOUBLE_FMT "g"
+ #define longdouble_t double
+ typedef double npy_longdouble;
+#else
+ #define NPY_LONGDOUBLE_FMT "Lg"
+ #define longdouble_t long double
+ typedef long double npy_longdouble;
+#endif
+
+#ifndef Py_USING_UNICODE
+#error Must use Python with unicode enabled.
+#endif
+
+
+typedef signed char npy_byte;
+typedef unsigned char npy_ubyte;
+typedef unsigned short npy_ushort;
+typedef unsigned int npy_uint;
+typedef unsigned long npy_ulong;
+
+/* These are for completeness */
+typedef char npy_char;
+typedef short npy_short;
+typedef int npy_int;
+typedef long npy_long;
+typedef float npy_float;
+typedef double npy_double;
+
+typedef Py_hash_t npy_hash_t;
+#define NPY_SIZEOF_HASH_T NPY_SIZEOF_INTP
+
+#if defined(__cplusplus)
+
+typedef struct
+{
+ double _Val[2];
+} npy_cdouble;
+
+typedef struct
+{
+ float _Val[2];
+} npy_cfloat;
+
+typedef struct
+{
+ long double _Val[2];
+} npy_clongdouble;
+
+#else
+
+#include
+
+
+#if defined(_MSC_VER) && !defined(__INTEL_COMPILER)
+typedef _Dcomplex npy_cdouble;
+typedef _Fcomplex npy_cfloat;
+typedef _Lcomplex npy_clongdouble;
+#else /* !defined(_MSC_VER) || defined(__INTEL_COMPILER) */
+typedef double _Complex npy_cdouble;
+typedef float _Complex npy_cfloat;
+typedef longdouble_t _Complex npy_clongdouble;
+#endif
+
+#endif
+
+/*
+ * numarray-style bit-width typedefs
+ */
+#define NPY_MAX_INT8 127
+#define NPY_MIN_INT8 -128
+#define NPY_MAX_UINT8 255
+#define NPY_MAX_INT16 32767
+#define NPY_MIN_INT16 -32768
+#define NPY_MAX_UINT16 65535
+#define NPY_MAX_INT32 2147483647
+#define NPY_MIN_INT32 (-NPY_MAX_INT32 - 1)
+#define NPY_MAX_UINT32 4294967295U
+#define NPY_MAX_INT64 NPY_LONGLONG_SUFFIX(9223372036854775807)
+#define NPY_MIN_INT64 (-NPY_MAX_INT64 - NPY_LONGLONG_SUFFIX(1))
+#define NPY_MAX_UINT64 NPY_ULONGLONG_SUFFIX(18446744073709551615)
+#define NPY_MAX_INT128 NPY_LONGLONG_SUFFIX(85070591730234615865843651857942052864)
+#define NPY_MIN_INT128 (-NPY_MAX_INT128 - NPY_LONGLONG_SUFFIX(1))
+#define NPY_MAX_UINT128 NPY_ULONGLONG_SUFFIX(170141183460469231731687303715884105728)
+#define NPY_MAX_INT256 NPY_LONGLONG_SUFFIX(57896044618658097711785492504343953926634992332820282019728792003956564819967)
+#define NPY_MIN_INT256 (-NPY_MAX_INT256 - NPY_LONGLONG_SUFFIX(1))
+#define NPY_MAX_UINT256 NPY_ULONGLONG_SUFFIX(115792089237316195423570985008687907853269984665640564039457584007913129639935)
+#define NPY_MIN_DATETIME NPY_MIN_INT64
+#define NPY_MAX_DATETIME NPY_MAX_INT64
+#define NPY_MIN_TIMEDELTA NPY_MIN_INT64
+#define NPY_MAX_TIMEDELTA NPY_MAX_INT64
+
+ /* Need to find the number of bits for each type and
+ make definitions accordingly.
+
+ C states that sizeof(char) == 1 by definition
+
+ So, just using the sizeof keyword won't help.
+
+ It also looks like Python itself uses sizeof(char) quite a
+ bit, which by definition should be 1 all the time.
+
+ Idea: Make Use of CHAR_BIT which should tell us how many
+ BITS per CHARACTER
+ */
+
+ /* Include platform definitions -- These are in the C89/90 standard */
+#include
+#define NPY_MAX_BYTE SCHAR_MAX
+#define NPY_MIN_BYTE SCHAR_MIN
+#define NPY_MAX_UBYTE UCHAR_MAX
+#define NPY_MAX_SHORT SHRT_MAX
+#define NPY_MIN_SHORT SHRT_MIN
+#define NPY_MAX_USHORT USHRT_MAX
+#define NPY_MAX_INT INT_MAX
+#ifndef INT_MIN
+#define INT_MIN (-INT_MAX - 1)
+#endif
+#define NPY_MIN_INT INT_MIN
+#define NPY_MAX_UINT UINT_MAX
+#define NPY_MAX_LONG LONG_MAX
+#define NPY_MIN_LONG LONG_MIN
+#define NPY_MAX_ULONG ULONG_MAX
+
+#define NPY_BITSOF_BOOL (sizeof(npy_bool) * CHAR_BIT)
+#define NPY_BITSOF_CHAR CHAR_BIT
+#define NPY_BITSOF_BYTE (NPY_SIZEOF_BYTE * CHAR_BIT)
+#define NPY_BITSOF_SHORT (NPY_SIZEOF_SHORT * CHAR_BIT)
+#define NPY_BITSOF_INT (NPY_SIZEOF_INT * CHAR_BIT)
+#define NPY_BITSOF_LONG (NPY_SIZEOF_LONG * CHAR_BIT)
+#define NPY_BITSOF_LONGLONG (NPY_SIZEOF_LONGLONG * CHAR_BIT)
+#define NPY_BITSOF_INTP (NPY_SIZEOF_INTP * CHAR_BIT)
+#define NPY_BITSOF_HALF (NPY_SIZEOF_HALF * CHAR_BIT)
+#define NPY_BITSOF_FLOAT (NPY_SIZEOF_FLOAT * CHAR_BIT)
+#define NPY_BITSOF_DOUBLE (NPY_SIZEOF_DOUBLE * CHAR_BIT)
+#define NPY_BITSOF_LONGDOUBLE (NPY_SIZEOF_LONGDOUBLE * CHAR_BIT)
+#define NPY_BITSOF_CFLOAT (NPY_SIZEOF_CFLOAT * CHAR_BIT)
+#define NPY_BITSOF_CDOUBLE (NPY_SIZEOF_CDOUBLE * CHAR_BIT)
+#define NPY_BITSOF_CLONGDOUBLE (NPY_SIZEOF_CLONGDOUBLE * CHAR_BIT)
+#define NPY_BITSOF_DATETIME (NPY_SIZEOF_DATETIME * CHAR_BIT)
+#define NPY_BITSOF_TIMEDELTA (NPY_SIZEOF_TIMEDELTA * CHAR_BIT)
+
+#if NPY_BITSOF_LONG == 8
+#define NPY_INT8 NPY_LONG
+#define NPY_UINT8 NPY_ULONG
+ typedef long npy_int8;
+ typedef unsigned long npy_uint8;
+#define PyInt8ScalarObject PyLongScalarObject
+#define PyInt8ArrType_Type PyLongArrType_Type
+#define PyUInt8ScalarObject PyULongScalarObject
+#define PyUInt8ArrType_Type PyULongArrType_Type
+#define NPY_INT8_FMT NPY_LONG_FMT
+#define NPY_UINT8_FMT NPY_ULONG_FMT
+#elif NPY_BITSOF_LONG == 16
+#define NPY_INT16 NPY_LONG
+#define NPY_UINT16 NPY_ULONG
+ typedef long npy_int16;
+ typedef unsigned long npy_uint16;
+#define PyInt16ScalarObject PyLongScalarObject
+#define PyInt16ArrType_Type PyLongArrType_Type
+#define PyUInt16ScalarObject PyULongScalarObject
+#define PyUInt16ArrType_Type PyULongArrType_Type
+#define NPY_INT16_FMT NPY_LONG_FMT
+#define NPY_UINT16_FMT NPY_ULONG_FMT
+#elif NPY_BITSOF_LONG == 32
+#define NPY_INT32 NPY_LONG
+#define NPY_UINT32 NPY_ULONG
+ typedef long npy_int32;
+ typedef unsigned long npy_uint32;
+ typedef unsigned long npy_ucs4;
+#define PyInt32ScalarObject PyLongScalarObject
+#define PyInt32ArrType_Type PyLongArrType_Type
+#define PyUInt32ScalarObject PyULongScalarObject
+#define PyUInt32ArrType_Type PyULongArrType_Type
+#define NPY_INT32_FMT NPY_LONG_FMT
+#define NPY_UINT32_FMT NPY_ULONG_FMT
+#elif NPY_BITSOF_LONG == 64
+#define NPY_INT64 NPY_LONG
+#define NPY_UINT64 NPY_ULONG
+ typedef long npy_int64;
+ typedef unsigned long npy_uint64;
+#define PyInt64ScalarObject PyLongScalarObject
+#define PyInt64ArrType_Type PyLongArrType_Type
+#define PyUInt64ScalarObject PyULongScalarObject
+#define PyUInt64ArrType_Type PyULongArrType_Type
+#define NPY_INT64_FMT NPY_LONG_FMT
+#define NPY_UINT64_FMT NPY_ULONG_FMT
+#define MyPyLong_FromInt64 PyLong_FromLong
+#define MyPyLong_AsInt64 PyLong_AsLong
+#elif NPY_BITSOF_LONG == 128
+#define NPY_INT128 NPY_LONG
+#define NPY_UINT128 NPY_ULONG
+ typedef long npy_int128;
+ typedef unsigned long npy_uint128;
+#define PyInt128ScalarObject PyLongScalarObject
+#define PyInt128ArrType_Type PyLongArrType_Type
+#define PyUInt128ScalarObject PyULongScalarObject
+#define PyUInt128ArrType_Type PyULongArrType_Type
+#define NPY_INT128_FMT NPY_LONG_FMT
+#define NPY_UINT128_FMT NPY_ULONG_FMT
+#endif
+
+#if NPY_BITSOF_LONGLONG == 8
+# ifndef NPY_INT8
+# define NPY_INT8 NPY_LONGLONG
+# define NPY_UINT8 NPY_ULONGLONG
+ typedef npy_longlong npy_int8;
+ typedef npy_ulonglong npy_uint8;
+# define PyInt8ScalarObject PyLongLongScalarObject
+# define PyInt8ArrType_Type PyLongLongArrType_Type
+# define PyUInt8ScalarObject PyULongLongScalarObject
+# define PyUInt8ArrType_Type PyULongLongArrType_Type
+#define NPY_INT8_FMT NPY_LONGLONG_FMT
+#define NPY_UINT8_FMT NPY_ULONGLONG_FMT
+# endif
+# define NPY_MAX_LONGLONG NPY_MAX_INT8
+# define NPY_MIN_LONGLONG NPY_MIN_INT8
+# define NPY_MAX_ULONGLONG NPY_MAX_UINT8
+#elif NPY_BITSOF_LONGLONG == 16
+# ifndef NPY_INT16
+# define NPY_INT16 NPY_LONGLONG
+# define NPY_UINT16 NPY_ULONGLONG
+ typedef npy_longlong npy_int16;
+ typedef npy_ulonglong npy_uint16;
+# define PyInt16ScalarObject PyLongLongScalarObject
+# define PyInt16ArrType_Type PyLongLongArrType_Type
+# define PyUInt16ScalarObject PyULongLongScalarObject
+# define PyUInt16ArrType_Type PyULongLongArrType_Type
+#define NPY_INT16_FMT NPY_LONGLONG_FMT
+#define NPY_UINT16_FMT NPY_ULONGLONG_FMT
+# endif
+# define NPY_MAX_LONGLONG NPY_MAX_INT16
+# define NPY_MIN_LONGLONG NPY_MIN_INT16
+# define NPY_MAX_ULONGLONG NPY_MAX_UINT16
+#elif NPY_BITSOF_LONGLONG == 32
+# ifndef NPY_INT32
+# define NPY_INT32 NPY_LONGLONG
+# define NPY_UINT32 NPY_ULONGLONG
+ typedef npy_longlong npy_int32;
+ typedef npy_ulonglong npy_uint32;
+ typedef npy_ulonglong npy_ucs4;
+# define PyInt32ScalarObject PyLongLongScalarObject
+# define PyInt32ArrType_Type PyLongLongArrType_Type
+# define PyUInt32ScalarObject PyULongLongScalarObject
+# define PyUInt32ArrType_Type PyULongLongArrType_Type
+#define NPY_INT32_FMT NPY_LONGLONG_FMT
+#define NPY_UINT32_FMT NPY_ULONGLONG_FMT
+# endif
+# define NPY_MAX_LONGLONG NPY_MAX_INT32
+# define NPY_MIN_LONGLONG NPY_MIN_INT32
+# define NPY_MAX_ULONGLONG NPY_MAX_UINT32
+#elif NPY_BITSOF_LONGLONG == 64
+# ifndef NPY_INT64
+# define NPY_INT64 NPY_LONGLONG
+# define NPY_UINT64 NPY_ULONGLONG
+ typedef npy_longlong npy_int64;
+ typedef npy_ulonglong npy_uint64;
+# define PyInt64ScalarObject PyLongLongScalarObject
+# define PyInt64ArrType_Type PyLongLongArrType_Type
+# define PyUInt64ScalarObject PyULongLongScalarObject
+# define PyUInt64ArrType_Type PyULongLongArrType_Type
+#define NPY_INT64_FMT NPY_LONGLONG_FMT
+#define NPY_UINT64_FMT NPY_ULONGLONG_FMT
+# define MyPyLong_FromInt64 PyLong_FromLongLong
+# define MyPyLong_AsInt64 PyLong_AsLongLong
+# endif
+# define NPY_MAX_LONGLONG NPY_MAX_INT64
+# define NPY_MIN_LONGLONG NPY_MIN_INT64
+# define NPY_MAX_ULONGLONG NPY_MAX_UINT64
+#elif NPY_BITSOF_LONGLONG == 128
+# ifndef NPY_INT128
+# define NPY_INT128 NPY_LONGLONG
+# define NPY_UINT128 NPY_ULONGLONG
+ typedef npy_longlong npy_int128;
+ typedef npy_ulonglong npy_uint128;
+# define PyInt128ScalarObject PyLongLongScalarObject
+# define PyInt128ArrType_Type PyLongLongArrType_Type
+# define PyUInt128ScalarObject PyULongLongScalarObject
+# define PyUInt128ArrType_Type PyULongLongArrType_Type
+#define NPY_INT128_FMT NPY_LONGLONG_FMT
+#define NPY_UINT128_FMT NPY_ULONGLONG_FMT
+# endif
+# define NPY_MAX_LONGLONG NPY_MAX_INT128
+# define NPY_MIN_LONGLONG NPY_MIN_INT128
+# define NPY_MAX_ULONGLONG NPY_MAX_UINT128
+#elif NPY_BITSOF_LONGLONG == 256
+# define NPY_INT256 NPY_LONGLONG
+# define NPY_UINT256 NPY_ULONGLONG
+ typedef npy_longlong npy_int256;
+ typedef npy_ulonglong npy_uint256;
+# define PyInt256ScalarObject PyLongLongScalarObject
+# define PyInt256ArrType_Type PyLongLongArrType_Type
+# define PyUInt256ScalarObject PyULongLongScalarObject
+# define PyUInt256ArrType_Type PyULongLongArrType_Type
+#define NPY_INT256_FMT NPY_LONGLONG_FMT
+#define NPY_UINT256_FMT NPY_ULONGLONG_FMT
+# define NPY_MAX_LONGLONG NPY_MAX_INT256
+# define NPY_MIN_LONGLONG NPY_MIN_INT256
+# define NPY_MAX_ULONGLONG NPY_MAX_UINT256
+#endif
+
+#if NPY_BITSOF_INT == 8
+#ifndef NPY_INT8
+#define NPY_INT8 NPY_INT
+#define NPY_UINT8 NPY_UINT
+ typedef int npy_int8;
+ typedef unsigned int npy_uint8;
+# define PyInt8ScalarObject PyIntScalarObject
+# define PyInt8ArrType_Type PyIntArrType_Type
+# define PyUInt8ScalarObject PyUIntScalarObject
+# define PyUInt8ArrType_Type PyUIntArrType_Type
+#define NPY_INT8_FMT NPY_INT_FMT
+#define NPY_UINT8_FMT NPY_UINT_FMT
+#endif
+#elif NPY_BITSOF_INT == 16
+#ifndef NPY_INT16
+#define NPY_INT16 NPY_INT
+#define NPY_UINT16 NPY_UINT
+ typedef int npy_int16;
+ typedef unsigned int npy_uint16;
+# define PyInt16ScalarObject PyIntScalarObject
+# define PyInt16ArrType_Type PyIntArrType_Type
+# define PyUInt16ScalarObject PyIntUScalarObject
+# define PyUInt16ArrType_Type PyIntUArrType_Type
+#define NPY_INT16_FMT NPY_INT_FMT
+#define NPY_UINT16_FMT NPY_UINT_FMT
+#endif
+#elif NPY_BITSOF_INT == 32
+#ifndef NPY_INT32
+#define NPY_INT32 NPY_INT
+#define NPY_UINT32 NPY_UINT
+ typedef int npy_int32;
+ typedef unsigned int npy_uint32;
+ typedef unsigned int npy_ucs4;
+# define PyInt32ScalarObject PyIntScalarObject
+# define PyInt32ArrType_Type PyIntArrType_Type
+# define PyUInt32ScalarObject PyUIntScalarObject
+# define PyUInt32ArrType_Type PyUIntArrType_Type
+#define NPY_INT32_FMT NPY_INT_FMT
+#define NPY_UINT32_FMT NPY_UINT_FMT
+#endif
+#elif NPY_BITSOF_INT == 64
+#ifndef NPY_INT64
+#define NPY_INT64 NPY_INT
+#define NPY_UINT64 NPY_UINT
+ typedef int npy_int64;
+ typedef unsigned int npy_uint64;
+# define PyInt64ScalarObject PyIntScalarObject
+# define PyInt64ArrType_Type PyIntArrType_Type
+# define PyUInt64ScalarObject PyUIntScalarObject
+# define PyUInt64ArrType_Type PyUIntArrType_Type
+#define NPY_INT64_FMT NPY_INT_FMT
+#define NPY_UINT64_FMT NPY_UINT_FMT
+# define MyPyLong_FromInt64 PyLong_FromLong
+# define MyPyLong_AsInt64 PyLong_AsLong
+#endif
+#elif NPY_BITSOF_INT == 128
+#ifndef NPY_INT128
+#define NPY_INT128 NPY_INT
+#define NPY_UINT128 NPY_UINT
+ typedef int npy_int128;
+ typedef unsigned int npy_uint128;
+# define PyInt128ScalarObject PyIntScalarObject
+# define PyInt128ArrType_Type PyIntArrType_Type
+# define PyUInt128ScalarObject PyUIntScalarObject
+# define PyUInt128ArrType_Type PyUIntArrType_Type
+#define NPY_INT128_FMT NPY_INT_FMT
+#define NPY_UINT128_FMT NPY_UINT_FMT
+#endif
+#endif
+
+#if NPY_BITSOF_SHORT == 8
+#ifndef NPY_INT8
+#define NPY_INT8 NPY_SHORT
+#define NPY_UINT8 NPY_USHORT
+ typedef short npy_int8;
+ typedef unsigned short npy_uint8;
+# define PyInt8ScalarObject PyShortScalarObject
+# define PyInt8ArrType_Type PyShortArrType_Type
+# define PyUInt8ScalarObject PyUShortScalarObject
+# define PyUInt8ArrType_Type PyUShortArrType_Type
+#define NPY_INT8_FMT NPY_SHORT_FMT
+#define NPY_UINT8_FMT NPY_USHORT_FMT
+#endif
+#elif NPY_BITSOF_SHORT == 16
+#ifndef NPY_INT16
+#define NPY_INT16 NPY_SHORT
+#define NPY_UINT16 NPY_USHORT
+ typedef short npy_int16;
+ typedef unsigned short npy_uint16;
+# define PyInt16ScalarObject PyShortScalarObject
+# define PyInt16ArrType_Type PyShortArrType_Type
+# define PyUInt16ScalarObject PyUShortScalarObject
+# define PyUInt16ArrType_Type PyUShortArrType_Type
+#define NPY_INT16_FMT NPY_SHORT_FMT
+#define NPY_UINT16_FMT NPY_USHORT_FMT
+#endif
+#elif NPY_BITSOF_SHORT == 32
+#ifndef NPY_INT32
+#define NPY_INT32 NPY_SHORT
+#define NPY_UINT32 NPY_USHORT
+ typedef short npy_int32;
+ typedef unsigned short npy_uint32;
+ typedef unsigned short npy_ucs4;
+# define PyInt32ScalarObject PyShortScalarObject
+# define PyInt32ArrType_Type PyShortArrType_Type
+# define PyUInt32ScalarObject PyUShortScalarObject
+# define PyUInt32ArrType_Type PyUShortArrType_Type
+#define NPY_INT32_FMT NPY_SHORT_FMT
+#define NPY_UINT32_FMT NPY_USHORT_FMT
+#endif
+#elif NPY_BITSOF_SHORT == 64
+#ifndef NPY_INT64
+#define NPY_INT64 NPY_SHORT
+#define NPY_UINT64 NPY_USHORT
+ typedef short npy_int64;
+ typedef unsigned short npy_uint64;
+# define PyInt64ScalarObject PyShortScalarObject
+# define PyInt64ArrType_Type PyShortArrType_Type
+# define PyUInt64ScalarObject PyUShortScalarObject
+# define PyUInt64ArrType_Type PyUShortArrType_Type
+#define NPY_INT64_FMT NPY_SHORT_FMT
+#define NPY_UINT64_FMT NPY_USHORT_FMT
+# define MyPyLong_FromInt64 PyLong_FromLong
+# define MyPyLong_AsInt64 PyLong_AsLong
+#endif
+#elif NPY_BITSOF_SHORT == 128
+#ifndef NPY_INT128
+#define NPY_INT128 NPY_SHORT
+#define NPY_UINT128 NPY_USHORT
+ typedef short npy_int128;
+ typedef unsigned short npy_uint128;
+# define PyInt128ScalarObject PyShortScalarObject
+# define PyInt128ArrType_Type PyShortArrType_Type
+# define PyUInt128ScalarObject PyUShortScalarObject
+# define PyUInt128ArrType_Type PyUShortArrType_Type
+#define NPY_INT128_FMT NPY_SHORT_FMT
+#define NPY_UINT128_FMT NPY_USHORT_FMT
+#endif
+#endif
+
+
+#if NPY_BITSOF_CHAR == 8
+#ifndef NPY_INT8
+#define NPY_INT8 NPY_BYTE
+#define NPY_UINT8 NPY_UBYTE
+ typedef signed char npy_int8;
+ typedef unsigned char npy_uint8;
+# define PyInt8ScalarObject PyByteScalarObject
+# define PyInt8ArrType_Type PyByteArrType_Type
+# define PyUInt8ScalarObject PyUByteScalarObject
+# define PyUInt8ArrType_Type PyUByteArrType_Type
+#define NPY_INT8_FMT NPY_BYTE_FMT
+#define NPY_UINT8_FMT NPY_UBYTE_FMT
+#endif
+#elif NPY_BITSOF_CHAR == 16
+#ifndef NPY_INT16
+#define NPY_INT16 NPY_BYTE
+#define NPY_UINT16 NPY_UBYTE
+ typedef signed char npy_int16;
+ typedef unsigned char npy_uint16;
+# define PyInt16ScalarObject PyByteScalarObject
+# define PyInt16ArrType_Type PyByteArrType_Type
+# define PyUInt16ScalarObject PyUByteScalarObject
+# define PyUInt16ArrType_Type PyUByteArrType_Type
+#define NPY_INT16_FMT NPY_BYTE_FMT
+#define NPY_UINT16_FMT NPY_UBYTE_FMT
+#endif
+#elif NPY_BITSOF_CHAR == 32
+#ifndef NPY_INT32
+#define NPY_INT32 NPY_BYTE
+#define NPY_UINT32 NPY_UBYTE
+ typedef signed char npy_int32;
+ typedef unsigned char npy_uint32;
+ typedef unsigned char npy_ucs4;
+# define PyInt32ScalarObject PyByteScalarObject
+# define PyInt32ArrType_Type PyByteArrType_Type
+# define PyUInt32ScalarObject PyUByteScalarObject
+# define PyUInt32ArrType_Type PyUByteArrType_Type
+#define NPY_INT32_FMT NPY_BYTE_FMT
+#define NPY_UINT32_FMT NPY_UBYTE_FMT
+#endif
+#elif NPY_BITSOF_CHAR == 64
+#ifndef NPY_INT64
+#define NPY_INT64 NPY_BYTE
+#define NPY_UINT64 NPY_UBYTE
+ typedef signed char npy_int64;
+ typedef unsigned char npy_uint64;
+# define PyInt64ScalarObject PyByteScalarObject
+# define PyInt64ArrType_Type PyByteArrType_Type
+# define PyUInt64ScalarObject PyUByteScalarObject
+# define PyUInt64ArrType_Type PyUByteArrType_Type
+#define NPY_INT64_FMT NPY_BYTE_FMT
+#define NPY_UINT64_FMT NPY_UBYTE_FMT
+# define MyPyLong_FromInt64 PyLong_FromLong
+# define MyPyLong_AsInt64 PyLong_AsLong
+#endif
+#elif NPY_BITSOF_CHAR == 128
+#ifndef NPY_INT128
+#define NPY_INT128 NPY_BYTE
+#define NPY_UINT128 NPY_UBYTE
+ typedef signed char npy_int128;
+ typedef unsigned char npy_uint128;
+# define PyInt128ScalarObject PyByteScalarObject
+# define PyInt128ArrType_Type PyByteArrType_Type
+# define PyUInt128ScalarObject PyUByteScalarObject
+# define PyUInt128ArrType_Type PyUByteArrType_Type
+#define NPY_INT128_FMT NPY_BYTE_FMT
+#define NPY_UINT128_FMT NPY_UBYTE_FMT
+#endif
+#endif
+
+
+
+#if NPY_BITSOF_DOUBLE == 32
+#ifndef NPY_FLOAT32
+#define NPY_FLOAT32 NPY_DOUBLE
+#define NPY_COMPLEX64 NPY_CDOUBLE
+ typedef double npy_float32;
+ typedef npy_cdouble npy_complex64;
+# define PyFloat32ScalarObject PyDoubleScalarObject
+# define PyComplex64ScalarObject PyCDoubleScalarObject
+# define PyFloat32ArrType_Type PyDoubleArrType_Type
+# define PyComplex64ArrType_Type PyCDoubleArrType_Type
+#define NPY_FLOAT32_FMT NPY_DOUBLE_FMT
+#define NPY_COMPLEX64_FMT NPY_CDOUBLE_FMT
+#endif
+#elif NPY_BITSOF_DOUBLE == 64
+#ifndef NPY_FLOAT64
+#define NPY_FLOAT64 NPY_DOUBLE
+#define NPY_COMPLEX128 NPY_CDOUBLE
+ typedef double npy_float64;
+ typedef npy_cdouble npy_complex128;
+# define PyFloat64ScalarObject PyDoubleScalarObject
+# define PyComplex128ScalarObject PyCDoubleScalarObject
+# define PyFloat64ArrType_Type PyDoubleArrType_Type
+# define PyComplex128ArrType_Type PyCDoubleArrType_Type
+#define NPY_FLOAT64_FMT NPY_DOUBLE_FMT
+#define NPY_COMPLEX128_FMT NPY_CDOUBLE_FMT
+#endif
+#elif NPY_BITSOF_DOUBLE == 80
+#ifndef NPY_FLOAT80
+#define NPY_FLOAT80 NPY_DOUBLE
+#define NPY_COMPLEX160 NPY_CDOUBLE
+ typedef double npy_float80;
+ typedef npy_cdouble npy_complex160;
+# define PyFloat80ScalarObject PyDoubleScalarObject
+# define PyComplex160ScalarObject PyCDoubleScalarObject
+# define PyFloat80ArrType_Type PyDoubleArrType_Type
+# define PyComplex160ArrType_Type PyCDoubleArrType_Type
+#define NPY_FLOAT80_FMT NPY_DOUBLE_FMT
+#define NPY_COMPLEX160_FMT NPY_CDOUBLE_FMT
+#endif
+#elif NPY_BITSOF_DOUBLE == 96
+#ifndef NPY_FLOAT96
+#define NPY_FLOAT96 NPY_DOUBLE
+#define NPY_COMPLEX192 NPY_CDOUBLE
+ typedef double npy_float96;
+ typedef npy_cdouble npy_complex192;
+# define PyFloat96ScalarObject PyDoubleScalarObject
+# define PyComplex192ScalarObject PyCDoubleScalarObject
+# define PyFloat96ArrType_Type PyDoubleArrType_Type
+# define PyComplex192ArrType_Type PyCDoubleArrType_Type
+#define NPY_FLOAT96_FMT NPY_DOUBLE_FMT
+#define NPY_COMPLEX192_FMT NPY_CDOUBLE_FMT
+#endif
+#elif NPY_BITSOF_DOUBLE == 128
+#ifndef NPY_FLOAT128
+#define NPY_FLOAT128 NPY_DOUBLE
+#define NPY_COMPLEX256 NPY_CDOUBLE
+ typedef double npy_float128;
+ typedef npy_cdouble npy_complex256;
+# define PyFloat128ScalarObject PyDoubleScalarObject
+# define PyComplex256ScalarObject PyCDoubleScalarObject
+# define PyFloat128ArrType_Type PyDoubleArrType_Type
+# define PyComplex256ArrType_Type PyCDoubleArrType_Type
+#define NPY_FLOAT128_FMT NPY_DOUBLE_FMT
+#define NPY_COMPLEX256_FMT NPY_CDOUBLE_FMT
+#endif
+#endif
+
+
+
+#if NPY_BITSOF_FLOAT == 32
+#ifndef NPY_FLOAT32
+#define NPY_FLOAT32 NPY_FLOAT
+#define NPY_COMPLEX64 NPY_CFLOAT
+ typedef float npy_float32;
+ typedef npy_cfloat npy_complex64;
+# define PyFloat32ScalarObject PyFloatScalarObject
+# define PyComplex64ScalarObject PyCFloatScalarObject
+# define PyFloat32ArrType_Type PyFloatArrType_Type
+# define PyComplex64ArrType_Type PyCFloatArrType_Type
+#define NPY_FLOAT32_FMT NPY_FLOAT_FMT
+#define NPY_COMPLEX64_FMT NPY_CFLOAT_FMT
+#endif
+#elif NPY_BITSOF_FLOAT == 64
+#ifndef NPY_FLOAT64
+#define NPY_FLOAT64 NPY_FLOAT
+#define NPY_COMPLEX128 NPY_CFLOAT
+ typedef float npy_float64;
+ typedef npy_cfloat npy_complex128;
+# define PyFloat64ScalarObject PyFloatScalarObject
+# define PyComplex128ScalarObject PyCFloatScalarObject
+# define PyFloat64ArrType_Type PyFloatArrType_Type
+# define PyComplex128ArrType_Type PyCFloatArrType_Type
+#define NPY_FLOAT64_FMT NPY_FLOAT_FMT
+#define NPY_COMPLEX128_FMT NPY_CFLOAT_FMT
+#endif
+#elif NPY_BITSOF_FLOAT == 80
+#ifndef NPY_FLOAT80
+#define NPY_FLOAT80 NPY_FLOAT
+#define NPY_COMPLEX160 NPY_CFLOAT
+ typedef float npy_float80;
+ typedef npy_cfloat npy_complex160;
+# define PyFloat80ScalarObject PyFloatScalarObject
+# define PyComplex160ScalarObject PyCFloatScalarObject
+# define PyFloat80ArrType_Type PyFloatArrType_Type
+# define PyComplex160ArrType_Type PyCFloatArrType_Type
+#define NPY_FLOAT80_FMT NPY_FLOAT_FMT
+#define NPY_COMPLEX160_FMT NPY_CFLOAT_FMT
+#endif
+#elif NPY_BITSOF_FLOAT == 96
+#ifndef NPY_FLOAT96
+#define NPY_FLOAT96 NPY_FLOAT
+#define NPY_COMPLEX192 NPY_CFLOAT
+ typedef float npy_float96;
+ typedef npy_cfloat npy_complex192;
+# define PyFloat96ScalarObject PyFloatScalarObject
+# define PyComplex192ScalarObject PyCFloatScalarObject
+# define PyFloat96ArrType_Type PyFloatArrType_Type
+# define PyComplex192ArrType_Type PyCFloatArrType_Type
+#define NPY_FLOAT96_FMT NPY_FLOAT_FMT
+#define NPY_COMPLEX192_FMT NPY_CFLOAT_FMT
+#endif
+#elif NPY_BITSOF_FLOAT == 128
+#ifndef NPY_FLOAT128
+#define NPY_FLOAT128 NPY_FLOAT
+#define NPY_COMPLEX256 NPY_CFLOAT
+ typedef float npy_float128;
+ typedef npy_cfloat npy_complex256;
+# define PyFloat128ScalarObject PyFloatScalarObject
+# define PyComplex256ScalarObject PyCFloatScalarObject
+# define PyFloat128ArrType_Type PyFloatArrType_Type
+# define PyComplex256ArrType_Type PyCFloatArrType_Type
+#define NPY_FLOAT128_FMT NPY_FLOAT_FMT
+#define NPY_COMPLEX256_FMT NPY_CFLOAT_FMT
+#endif
+#endif
+
+/* half/float16 isn't a floating-point type in C */
+#define NPY_FLOAT16 NPY_HALF
+typedef npy_uint16 npy_half;
+typedef npy_half npy_float16;
+
+#if NPY_BITSOF_LONGDOUBLE == 32
+#ifndef NPY_FLOAT32
+#define NPY_FLOAT32 NPY_LONGDOUBLE
+#define NPY_COMPLEX64 NPY_CLONGDOUBLE
+ typedef npy_longdouble npy_float32;
+ typedef npy_clongdouble npy_complex64;
+# define PyFloat32ScalarObject PyLongDoubleScalarObject
+# define PyComplex64ScalarObject PyCLongDoubleScalarObject
+# define PyFloat32ArrType_Type PyLongDoubleArrType_Type
+# define PyComplex64ArrType_Type PyCLongDoubleArrType_Type
+#define NPY_FLOAT32_FMT NPY_LONGDOUBLE_FMT
+#define NPY_COMPLEX64_FMT NPY_CLONGDOUBLE_FMT
+#endif
+#elif NPY_BITSOF_LONGDOUBLE == 64
+#ifndef NPY_FLOAT64
+#define NPY_FLOAT64 NPY_LONGDOUBLE
+#define NPY_COMPLEX128 NPY_CLONGDOUBLE
+ typedef npy_longdouble npy_float64;
+ typedef npy_clongdouble npy_complex128;
+# define PyFloat64ScalarObject PyLongDoubleScalarObject
+# define PyComplex128ScalarObject PyCLongDoubleScalarObject
+# define PyFloat64ArrType_Type PyLongDoubleArrType_Type
+# define PyComplex128ArrType_Type PyCLongDoubleArrType_Type
+#define NPY_FLOAT64_FMT NPY_LONGDOUBLE_FMT
+#define NPY_COMPLEX128_FMT NPY_CLONGDOUBLE_FMT
+#endif
+#elif NPY_BITSOF_LONGDOUBLE == 80
+#ifndef NPY_FLOAT80
+#define NPY_FLOAT80 NPY_LONGDOUBLE
+#define NPY_COMPLEX160 NPY_CLONGDOUBLE
+ typedef npy_longdouble npy_float80;
+ typedef npy_clongdouble npy_complex160;
+# define PyFloat80ScalarObject PyLongDoubleScalarObject
+# define PyComplex160ScalarObject PyCLongDoubleScalarObject
+# define PyFloat80ArrType_Type PyLongDoubleArrType_Type
+# define PyComplex160ArrType_Type PyCLongDoubleArrType_Type
+#define NPY_FLOAT80_FMT NPY_LONGDOUBLE_FMT
+#define NPY_COMPLEX160_FMT NPY_CLONGDOUBLE_FMT
+#endif
+#elif NPY_BITSOF_LONGDOUBLE == 96
+#ifndef NPY_FLOAT96
+#define NPY_FLOAT96 NPY_LONGDOUBLE
+#define NPY_COMPLEX192 NPY_CLONGDOUBLE
+ typedef npy_longdouble npy_float96;
+ typedef npy_clongdouble npy_complex192;
+# define PyFloat96ScalarObject PyLongDoubleScalarObject
+# define PyComplex192ScalarObject PyCLongDoubleScalarObject
+# define PyFloat96ArrType_Type PyLongDoubleArrType_Type
+# define PyComplex192ArrType_Type PyCLongDoubleArrType_Type
+#define NPY_FLOAT96_FMT NPY_LONGDOUBLE_FMT
+#define NPY_COMPLEX192_FMT NPY_CLONGDOUBLE_FMT
+#endif
+#elif NPY_BITSOF_LONGDOUBLE == 128
+#ifndef NPY_FLOAT128
+#define NPY_FLOAT128 NPY_LONGDOUBLE
+#define NPY_COMPLEX256 NPY_CLONGDOUBLE
+ typedef npy_longdouble npy_float128;
+ typedef npy_clongdouble npy_complex256;
+# define PyFloat128ScalarObject PyLongDoubleScalarObject
+# define PyComplex256ScalarObject PyCLongDoubleScalarObject
+# define PyFloat128ArrType_Type PyLongDoubleArrType_Type
+# define PyComplex256ArrType_Type PyCLongDoubleArrType_Type
+#define NPY_FLOAT128_FMT NPY_LONGDOUBLE_FMT
+#define NPY_COMPLEX256_FMT NPY_CLONGDOUBLE_FMT
+#endif
+#elif NPY_BITSOF_LONGDOUBLE == 256
+#define NPY_FLOAT256 NPY_LONGDOUBLE
+#define NPY_COMPLEX512 NPY_CLONGDOUBLE
+ typedef npy_longdouble npy_float256;
+ typedef npy_clongdouble npy_complex512;
+# define PyFloat256ScalarObject PyLongDoubleScalarObject
+# define PyComplex512ScalarObject PyCLongDoubleScalarObject
+# define PyFloat256ArrType_Type PyLongDoubleArrType_Type
+# define PyComplex512ArrType_Type PyCLongDoubleArrType_Type
+#define NPY_FLOAT256_FMT NPY_LONGDOUBLE_FMT
+#define NPY_COMPLEX512_FMT NPY_CLONGDOUBLE_FMT
+#endif
+
+/* datetime typedefs */
+typedef npy_int64 npy_timedelta;
+typedef npy_int64 npy_datetime;
+#define NPY_DATETIME_FMT NPY_INT64_FMT
+#define NPY_TIMEDELTA_FMT NPY_INT64_FMT
+
+/* End of typedefs for numarray style bit-width names */
+
+#endif /* NUMPY_CORE_INCLUDE_NUMPY_NPY_COMMON_H_ */
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/npy_cpu.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/npy_cpu.h
new file mode 100644
index 0000000000000000000000000000000000000000..15f9f12931c82f0be8bfe6e32903754c5915485d
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/npy_cpu.h
@@ -0,0 +1,134 @@
+/*
+ * This set (target) cpu specific macros:
+ * - Possible values:
+ * NPY_CPU_X86
+ * NPY_CPU_AMD64
+ * NPY_CPU_PPC
+ * NPY_CPU_PPC64
+ * NPY_CPU_PPC64LE
+ * NPY_CPU_SPARC
+ * NPY_CPU_S390
+ * NPY_CPU_IA64
+ * NPY_CPU_HPPA
+ * NPY_CPU_ALPHA
+ * NPY_CPU_ARMEL
+ * NPY_CPU_ARMEB
+ * NPY_CPU_SH_LE
+ * NPY_CPU_SH_BE
+ * NPY_CPU_ARCEL
+ * NPY_CPU_ARCEB
+ * NPY_CPU_RISCV64
+ * NPY_CPU_RISCV32
+ * NPY_CPU_LOONGARCH
+ * NPY_CPU_WASM
+ */
+#ifndef NUMPY_CORE_INCLUDE_NUMPY_NPY_CPU_H_
+#define NUMPY_CORE_INCLUDE_NUMPY_NPY_CPU_H_
+
+#include "numpyconfig.h"
+
+#if defined( __i386__ ) || defined(i386) || defined(_M_IX86)
+ /*
+ * __i386__ is defined by gcc and Intel compiler on Linux,
+ * _M_IX86 by VS compiler,
+ * i386 by Sun compilers on opensolaris at least
+ */
+ #define NPY_CPU_X86
+#elif defined(__x86_64__) || defined(__amd64__) || defined(__x86_64) || defined(_M_AMD64)
+ /*
+ * both __x86_64__ and __amd64__ are defined by gcc
+ * __x86_64 defined by sun compiler on opensolaris at least
+ * _M_AMD64 defined by MS compiler
+ */
+ #define NPY_CPU_AMD64
+#elif defined(__powerpc64__) && defined(__LITTLE_ENDIAN__)
+ #define NPY_CPU_PPC64LE
+#elif defined(__powerpc64__) && defined(__BIG_ENDIAN__)
+ #define NPY_CPU_PPC64
+#elif defined(__ppc__) || defined(__powerpc__) || defined(_ARCH_PPC)
+ /*
+ * __ppc__ is defined by gcc, I remember having seen __powerpc__ once,
+ * but can't find it ATM
+ * _ARCH_PPC is used by at least gcc on AIX
+ * As __powerpc__ and _ARCH_PPC are also defined by PPC64 check
+ * for those specifically first before defaulting to ppc
+ */
+ #define NPY_CPU_PPC
+#elif defined(__sparc__) || defined(__sparc)
+ /* __sparc__ is defined by gcc and Forte (e.g. Sun) compilers */
+ #define NPY_CPU_SPARC
+#elif defined(__s390__)
+ #define NPY_CPU_S390
+#elif defined(__ia64)
+ #define NPY_CPU_IA64
+#elif defined(__hppa)
+ #define NPY_CPU_HPPA
+#elif defined(__alpha__)
+ #define NPY_CPU_ALPHA
+#elif defined(__arm__) || defined(__aarch64__) || defined(_M_ARM64)
+ /* _M_ARM64 is defined in MSVC for ARM64 compilation on Windows */
+ #if defined(__ARMEB__) || defined(__AARCH64EB__)
+ #if defined(__ARM_32BIT_STATE)
+ #define NPY_CPU_ARMEB_AARCH32
+ #elif defined(__ARM_64BIT_STATE)
+ #define NPY_CPU_ARMEB_AARCH64
+ #else
+ #define NPY_CPU_ARMEB
+ #endif
+ #elif defined(__ARMEL__) || defined(__AARCH64EL__) || defined(_M_ARM64)
+ #if defined(__ARM_32BIT_STATE)
+ #define NPY_CPU_ARMEL_AARCH32
+ #elif defined(__ARM_64BIT_STATE) || defined(_M_ARM64) || defined(__AARCH64EL__)
+ #define NPY_CPU_ARMEL_AARCH64
+ #else
+ #define NPY_CPU_ARMEL
+ #endif
+ #else
+ # error Unknown ARM CPU, please report this to numpy maintainers with \
+ information about your platform (OS, CPU and compiler)
+ #endif
+#elif defined(__sh__) && defined(__LITTLE_ENDIAN__)
+ #define NPY_CPU_SH_LE
+#elif defined(__sh__) && defined(__BIG_ENDIAN__)
+ #define NPY_CPU_SH_BE
+#elif defined(__MIPSEL__)
+ #define NPY_CPU_MIPSEL
+#elif defined(__MIPSEB__)
+ #define NPY_CPU_MIPSEB
+#elif defined(__or1k__)
+ #define NPY_CPU_OR1K
+#elif defined(__mc68000__)
+ #define NPY_CPU_M68K
+#elif defined(__arc__) && defined(__LITTLE_ENDIAN__)
+ #define NPY_CPU_ARCEL
+#elif defined(__arc__) && defined(__BIG_ENDIAN__)
+ #define NPY_CPU_ARCEB
+#elif defined(__riscv)
+ #if __riscv_xlen == 64
+ #define NPY_CPU_RISCV64
+ #elif __riscv_xlen == 32
+ #define NPY_CPU_RISCV32
+ #endif
+#elif defined(__loongarch__)
+ #define NPY_CPU_LOONGARCH
+#elif defined(__EMSCRIPTEN__)
+ /* __EMSCRIPTEN__ is defined by emscripten: an LLVM-to-Web compiler */
+ #define NPY_CPU_WASM
+#else
+ #error Unknown CPU, please report this to numpy maintainers with \
+ information about your platform (OS, CPU and compiler)
+#endif
+
+/*
+ * Except for the following architectures, memory access is limited to the natural
+ * alignment of data types otherwise it may lead to bus error or performance regression.
+ * For more details about unaligned access, see https://www.kernel.org/doc/Documentation/unaligned-memory-access.txt.
+*/
+#if defined(NPY_CPU_X86) || defined(NPY_CPU_AMD64) || defined(__aarch64__) || defined(__powerpc64__)
+ #define NPY_ALIGNMENT_REQUIRED 0
+#endif
+#ifndef NPY_ALIGNMENT_REQUIRED
+ #define NPY_ALIGNMENT_REQUIRED 1
+#endif
+
+#endif /* NUMPY_CORE_INCLUDE_NUMPY_NPY_CPU_H_ */
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/npy_endian.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/npy_endian.h
new file mode 100644
index 0000000000000000000000000000000000000000..09262120bf82c5065d1f914a5825ce2de0063d4d
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/npy_endian.h
@@ -0,0 +1,78 @@
+#ifndef NUMPY_CORE_INCLUDE_NUMPY_NPY_ENDIAN_H_
+#define NUMPY_CORE_INCLUDE_NUMPY_NPY_ENDIAN_H_
+
+/*
+ * NPY_BYTE_ORDER is set to the same value as BYTE_ORDER set by glibc in
+ * endian.h
+ */
+
+#if defined(NPY_HAVE_ENDIAN_H) || defined(NPY_HAVE_SYS_ENDIAN_H)
+ /* Use endian.h if available */
+
+ #if defined(NPY_HAVE_ENDIAN_H)
+ #include
+ #elif defined(NPY_HAVE_SYS_ENDIAN_H)
+ #include
+ #endif
+
+ #if defined(BYTE_ORDER) && defined(BIG_ENDIAN) && defined(LITTLE_ENDIAN)
+ #define NPY_BYTE_ORDER BYTE_ORDER
+ #define NPY_LITTLE_ENDIAN LITTLE_ENDIAN
+ #define NPY_BIG_ENDIAN BIG_ENDIAN
+ #elif defined(_BYTE_ORDER) && defined(_BIG_ENDIAN) && defined(_LITTLE_ENDIAN)
+ #define NPY_BYTE_ORDER _BYTE_ORDER
+ #define NPY_LITTLE_ENDIAN _LITTLE_ENDIAN
+ #define NPY_BIG_ENDIAN _BIG_ENDIAN
+ #elif defined(__BYTE_ORDER) && defined(__BIG_ENDIAN) && defined(__LITTLE_ENDIAN)
+ #define NPY_BYTE_ORDER __BYTE_ORDER
+ #define NPY_LITTLE_ENDIAN __LITTLE_ENDIAN
+ #define NPY_BIG_ENDIAN __BIG_ENDIAN
+ #endif
+#endif
+
+#ifndef NPY_BYTE_ORDER
+ /* Set endianness info using target CPU */
+ #include "npy_cpu.h"
+
+ #define NPY_LITTLE_ENDIAN 1234
+ #define NPY_BIG_ENDIAN 4321
+
+ #if defined(NPY_CPU_X86) \
+ || defined(NPY_CPU_AMD64) \
+ || defined(NPY_CPU_IA64) \
+ || defined(NPY_CPU_ALPHA) \
+ || defined(NPY_CPU_ARMEL) \
+ || defined(NPY_CPU_ARMEL_AARCH32) \
+ || defined(NPY_CPU_ARMEL_AARCH64) \
+ || defined(NPY_CPU_SH_LE) \
+ || defined(NPY_CPU_MIPSEL) \
+ || defined(NPY_CPU_PPC64LE) \
+ || defined(NPY_CPU_ARCEL) \
+ || defined(NPY_CPU_RISCV64) \
+ || defined(NPY_CPU_RISCV32) \
+ || defined(NPY_CPU_LOONGARCH) \
+ || defined(NPY_CPU_WASM)
+ #define NPY_BYTE_ORDER NPY_LITTLE_ENDIAN
+
+ #elif defined(NPY_CPU_PPC) \
+ || defined(NPY_CPU_SPARC) \
+ || defined(NPY_CPU_S390) \
+ || defined(NPY_CPU_HPPA) \
+ || defined(NPY_CPU_PPC64) \
+ || defined(NPY_CPU_ARMEB) \
+ || defined(NPY_CPU_ARMEB_AARCH32) \
+ || defined(NPY_CPU_ARMEB_AARCH64) \
+ || defined(NPY_CPU_SH_BE) \
+ || defined(NPY_CPU_MIPSEB) \
+ || defined(NPY_CPU_OR1K) \
+ || defined(NPY_CPU_M68K) \
+ || defined(NPY_CPU_ARCEB)
+ #define NPY_BYTE_ORDER NPY_BIG_ENDIAN
+
+ #else
+ #error Unknown CPU: can not set endianness
+ #endif
+
+#endif
+
+#endif /* NUMPY_CORE_INCLUDE_NUMPY_NPY_ENDIAN_H_ */
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/npy_math.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/npy_math.h
new file mode 100644
index 0000000000000000000000000000000000000000..abc784bc686c18d162a4730a7c60393622023aae
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/npy_math.h
@@ -0,0 +1,602 @@
+#ifndef NUMPY_CORE_INCLUDE_NUMPY_NPY_MATH_H_
+#define NUMPY_CORE_INCLUDE_NUMPY_NPY_MATH_H_
+
+#include
+
+#include
+
+/* By adding static inline specifiers to npy_math function definitions when
+ appropriate, compiler is given the opportunity to optimize */
+#if NPY_INLINE_MATH
+#define NPY_INPLACE static inline
+#else
+#define NPY_INPLACE
+#endif
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define PyArray_MAX(a,b) (((a)>(b))?(a):(b))
+#define PyArray_MIN(a,b) (((a)<(b))?(a):(b))
+
+/*
+ * NAN and INFINITY like macros (same behavior as glibc for NAN, same as C99
+ * for INFINITY)
+ *
+ * XXX: I should test whether INFINITY and NAN are available on the platform
+ */
+static inline float __npy_inff(void)
+{
+ const union { npy_uint32 __i; float __f;} __bint = {0x7f800000UL};
+ return __bint.__f;
+}
+
+static inline float __npy_nanf(void)
+{
+ const union { npy_uint32 __i; float __f;} __bint = {0x7fc00000UL};
+ return __bint.__f;
+}
+
+static inline float __npy_pzerof(void)
+{
+ const union { npy_uint32 __i; float __f;} __bint = {0x00000000UL};
+ return __bint.__f;
+}
+
+static inline float __npy_nzerof(void)
+{
+ const union { npy_uint32 __i; float __f;} __bint = {0x80000000UL};
+ return __bint.__f;
+}
+
+#define NPY_INFINITYF __npy_inff()
+#define NPY_NANF __npy_nanf()
+#define NPY_PZEROF __npy_pzerof()
+#define NPY_NZEROF __npy_nzerof()
+
+#define NPY_INFINITY ((npy_double)NPY_INFINITYF)
+#define NPY_NAN ((npy_double)NPY_NANF)
+#define NPY_PZERO ((npy_double)NPY_PZEROF)
+#define NPY_NZERO ((npy_double)NPY_NZEROF)
+
+#define NPY_INFINITYL ((npy_longdouble)NPY_INFINITYF)
+#define NPY_NANL ((npy_longdouble)NPY_NANF)
+#define NPY_PZEROL ((npy_longdouble)NPY_PZEROF)
+#define NPY_NZEROL ((npy_longdouble)NPY_NZEROF)
+
+/*
+ * Useful constants
+ */
+#define NPY_E 2.718281828459045235360287471352662498 /* e */
+#define NPY_LOG2E 1.442695040888963407359924681001892137 /* log_2 e */
+#define NPY_LOG10E 0.434294481903251827651128918916605082 /* log_10 e */
+#define NPY_LOGE2 0.693147180559945309417232121458176568 /* log_e 2 */
+#define NPY_LOGE10 2.302585092994045684017991454684364208 /* log_e 10 */
+#define NPY_PI 3.141592653589793238462643383279502884 /* pi */
+#define NPY_PI_2 1.570796326794896619231321691639751442 /* pi/2 */
+#define NPY_PI_4 0.785398163397448309615660845819875721 /* pi/4 */
+#define NPY_1_PI 0.318309886183790671537767526745028724 /* 1/pi */
+#define NPY_2_PI 0.636619772367581343075535053490057448 /* 2/pi */
+#define NPY_EULER 0.577215664901532860606512090082402431 /* Euler constant */
+#define NPY_SQRT2 1.414213562373095048801688724209698079 /* sqrt(2) */
+#define NPY_SQRT1_2 0.707106781186547524400844362104849039 /* 1/sqrt(2) */
+
+#define NPY_Ef 2.718281828459045235360287471352662498F /* e */
+#define NPY_LOG2Ef 1.442695040888963407359924681001892137F /* log_2 e */
+#define NPY_LOG10Ef 0.434294481903251827651128918916605082F /* log_10 e */
+#define NPY_LOGE2f 0.693147180559945309417232121458176568F /* log_e 2 */
+#define NPY_LOGE10f 2.302585092994045684017991454684364208F /* log_e 10 */
+#define NPY_PIf 3.141592653589793238462643383279502884F /* pi */
+#define NPY_PI_2f 1.570796326794896619231321691639751442F /* pi/2 */
+#define NPY_PI_4f 0.785398163397448309615660845819875721F /* pi/4 */
+#define NPY_1_PIf 0.318309886183790671537767526745028724F /* 1/pi */
+#define NPY_2_PIf 0.636619772367581343075535053490057448F /* 2/pi */
+#define NPY_EULERf 0.577215664901532860606512090082402431F /* Euler constant */
+#define NPY_SQRT2f 1.414213562373095048801688724209698079F /* sqrt(2) */
+#define NPY_SQRT1_2f 0.707106781186547524400844362104849039F /* 1/sqrt(2) */
+
+#define NPY_El 2.718281828459045235360287471352662498L /* e */
+#define NPY_LOG2El 1.442695040888963407359924681001892137L /* log_2 e */
+#define NPY_LOG10El 0.434294481903251827651128918916605082L /* log_10 e */
+#define NPY_LOGE2l 0.693147180559945309417232121458176568L /* log_e 2 */
+#define NPY_LOGE10l 2.302585092994045684017991454684364208L /* log_e 10 */
+#define NPY_PIl 3.141592653589793238462643383279502884L /* pi */
+#define NPY_PI_2l 1.570796326794896619231321691639751442L /* pi/2 */
+#define NPY_PI_4l 0.785398163397448309615660845819875721L /* pi/4 */
+#define NPY_1_PIl 0.318309886183790671537767526745028724L /* 1/pi */
+#define NPY_2_PIl 0.636619772367581343075535053490057448L /* 2/pi */
+#define NPY_EULERl 0.577215664901532860606512090082402431L /* Euler constant */
+#define NPY_SQRT2l 1.414213562373095048801688724209698079L /* sqrt(2) */
+#define NPY_SQRT1_2l 0.707106781186547524400844362104849039L /* 1/sqrt(2) */
+
+/*
+ * Integer functions.
+ */
+NPY_INPLACE npy_uint npy_gcdu(npy_uint a, npy_uint b);
+NPY_INPLACE npy_uint npy_lcmu(npy_uint a, npy_uint b);
+NPY_INPLACE npy_ulong npy_gcdul(npy_ulong a, npy_ulong b);
+NPY_INPLACE npy_ulong npy_lcmul(npy_ulong a, npy_ulong b);
+NPY_INPLACE npy_ulonglong npy_gcdull(npy_ulonglong a, npy_ulonglong b);
+NPY_INPLACE npy_ulonglong npy_lcmull(npy_ulonglong a, npy_ulonglong b);
+
+NPY_INPLACE npy_int npy_gcd(npy_int a, npy_int b);
+NPY_INPLACE npy_int npy_lcm(npy_int a, npy_int b);
+NPY_INPLACE npy_long npy_gcdl(npy_long a, npy_long b);
+NPY_INPLACE npy_long npy_lcml(npy_long a, npy_long b);
+NPY_INPLACE npy_longlong npy_gcdll(npy_longlong a, npy_longlong b);
+NPY_INPLACE npy_longlong npy_lcmll(npy_longlong a, npy_longlong b);
+
+NPY_INPLACE npy_ubyte npy_rshiftuhh(npy_ubyte a, npy_ubyte b);
+NPY_INPLACE npy_ubyte npy_lshiftuhh(npy_ubyte a, npy_ubyte b);
+NPY_INPLACE npy_ushort npy_rshiftuh(npy_ushort a, npy_ushort b);
+NPY_INPLACE npy_ushort npy_lshiftuh(npy_ushort a, npy_ushort b);
+NPY_INPLACE npy_uint npy_rshiftu(npy_uint a, npy_uint b);
+NPY_INPLACE npy_uint npy_lshiftu(npy_uint a, npy_uint b);
+NPY_INPLACE npy_ulong npy_rshiftul(npy_ulong a, npy_ulong b);
+NPY_INPLACE npy_ulong npy_lshiftul(npy_ulong a, npy_ulong b);
+NPY_INPLACE npy_ulonglong npy_rshiftull(npy_ulonglong a, npy_ulonglong b);
+NPY_INPLACE npy_ulonglong npy_lshiftull(npy_ulonglong a, npy_ulonglong b);
+
+NPY_INPLACE npy_byte npy_rshifthh(npy_byte a, npy_byte b);
+NPY_INPLACE npy_byte npy_lshifthh(npy_byte a, npy_byte b);
+NPY_INPLACE npy_short npy_rshifth(npy_short a, npy_short b);
+NPY_INPLACE npy_short npy_lshifth(npy_short a, npy_short b);
+NPY_INPLACE npy_int npy_rshift(npy_int a, npy_int b);
+NPY_INPLACE npy_int npy_lshift(npy_int a, npy_int b);
+NPY_INPLACE npy_long npy_rshiftl(npy_long a, npy_long b);
+NPY_INPLACE npy_long npy_lshiftl(npy_long a, npy_long b);
+NPY_INPLACE npy_longlong npy_rshiftll(npy_longlong a, npy_longlong b);
+NPY_INPLACE npy_longlong npy_lshiftll(npy_longlong a, npy_longlong b);
+
+NPY_INPLACE uint8_t npy_popcountuhh(npy_ubyte a);
+NPY_INPLACE uint8_t npy_popcountuh(npy_ushort a);
+NPY_INPLACE uint8_t npy_popcountu(npy_uint a);
+NPY_INPLACE uint8_t npy_popcountul(npy_ulong a);
+NPY_INPLACE uint8_t npy_popcountull(npy_ulonglong a);
+NPY_INPLACE uint8_t npy_popcounthh(npy_byte a);
+NPY_INPLACE uint8_t npy_popcounth(npy_short a);
+NPY_INPLACE uint8_t npy_popcount(npy_int a);
+NPY_INPLACE uint8_t npy_popcountl(npy_long a);
+NPY_INPLACE uint8_t npy_popcountll(npy_longlong a);
+
+/*
+ * C99 double math funcs that need fixups or are blocklist-able
+ */
+NPY_INPLACE double npy_sin(double x);
+NPY_INPLACE double npy_cos(double x);
+NPY_INPLACE double npy_tan(double x);
+NPY_INPLACE double npy_hypot(double x, double y);
+NPY_INPLACE double npy_log2(double x);
+NPY_INPLACE double npy_atan2(double x, double y);
+
+/* Mandatory C99 double math funcs, no blocklisting or fixups */
+/* defined for legacy reasons, should be deprecated at some point */
+#define npy_sinh sinh
+#define npy_cosh cosh
+#define npy_tanh tanh
+#define npy_asin asin
+#define npy_acos acos
+#define npy_atan atan
+#define npy_log log
+#define npy_log10 log10
+#define npy_cbrt cbrt
+#define npy_fabs fabs
+#define npy_ceil ceil
+#define npy_fmod fmod
+#define npy_floor floor
+#define npy_expm1 expm1
+#define npy_log1p log1p
+#define npy_acosh acosh
+#define npy_asinh asinh
+#define npy_atanh atanh
+#define npy_rint rint
+#define npy_trunc trunc
+#define npy_exp2 exp2
+#define npy_frexp frexp
+#define npy_ldexp ldexp
+#define npy_copysign copysign
+#define npy_exp exp
+#define npy_sqrt sqrt
+#define npy_pow pow
+#define npy_modf modf
+#define npy_nextafter nextafter
+
+double npy_spacing(double x);
+
+/*
+ * IEEE 754 fpu handling
+ */
+
+/* use builtins to avoid function calls in tight loops
+ * only available if npy_config.h is available (= numpys own build) */
+#ifdef HAVE___BUILTIN_ISNAN
+ #define npy_isnan(x) __builtin_isnan(x)
+#else
+ #define npy_isnan(x) isnan(x)
+#endif
+
+
+/* only available if npy_config.h is available (= numpys own build) */
+#ifdef HAVE___BUILTIN_ISFINITE
+ #define npy_isfinite(x) __builtin_isfinite(x)
+#else
+ #define npy_isfinite(x) isfinite((x))
+#endif
+
+/* only available if npy_config.h is available (= numpys own build) */
+#ifdef HAVE___BUILTIN_ISINF
+ #define npy_isinf(x) __builtin_isinf(x)
+#else
+ #define npy_isinf(x) isinf((x))
+#endif
+
+#define npy_signbit(x) signbit((x))
+
+/*
+ * float C99 math funcs that need fixups or are blocklist-able
+ */
+NPY_INPLACE float npy_sinf(float x);
+NPY_INPLACE float npy_cosf(float x);
+NPY_INPLACE float npy_tanf(float x);
+NPY_INPLACE float npy_expf(float x);
+NPY_INPLACE float npy_sqrtf(float x);
+NPY_INPLACE float npy_hypotf(float x, float y);
+NPY_INPLACE float npy_log2f(float x);
+NPY_INPLACE float npy_atan2f(float x, float y);
+NPY_INPLACE float npy_powf(float x, float y);
+NPY_INPLACE float npy_modff(float x, float* y);
+
+/* Mandatory C99 float math funcs, no blocklisting or fixups */
+/* defined for legacy reasons, should be deprecated at some point */
+
+#define npy_sinhf sinhf
+#define npy_coshf coshf
+#define npy_tanhf tanhf
+#define npy_asinf asinf
+#define npy_acosf acosf
+#define npy_atanf atanf
+#define npy_logf logf
+#define npy_log10f log10f
+#define npy_cbrtf cbrtf
+#define npy_fabsf fabsf
+#define npy_ceilf ceilf
+#define npy_fmodf fmodf
+#define npy_floorf floorf
+#define npy_expm1f expm1f
+#define npy_log1pf log1pf
+#define npy_asinhf asinhf
+#define npy_acoshf acoshf
+#define npy_atanhf atanhf
+#define npy_rintf rintf
+#define npy_truncf truncf
+#define npy_exp2f exp2f
+#define npy_frexpf frexpf
+#define npy_ldexpf ldexpf
+#define npy_copysignf copysignf
+#define npy_nextafterf nextafterf
+
+float npy_spacingf(float x);
+
+/*
+ * long double C99 double math funcs that need fixups or are blocklist-able
+ */
+NPY_INPLACE npy_longdouble npy_sinl(npy_longdouble x);
+NPY_INPLACE npy_longdouble npy_cosl(npy_longdouble x);
+NPY_INPLACE npy_longdouble npy_tanl(npy_longdouble x);
+NPY_INPLACE npy_longdouble npy_expl(npy_longdouble x);
+NPY_INPLACE npy_longdouble npy_sqrtl(npy_longdouble x);
+NPY_INPLACE npy_longdouble npy_hypotl(npy_longdouble x, npy_longdouble y);
+NPY_INPLACE npy_longdouble npy_log2l(npy_longdouble x);
+NPY_INPLACE npy_longdouble npy_atan2l(npy_longdouble x, npy_longdouble y);
+NPY_INPLACE npy_longdouble npy_powl(npy_longdouble x, npy_longdouble y);
+NPY_INPLACE npy_longdouble npy_modfl(npy_longdouble x, npy_longdouble* y);
+
+/* Mandatory C99 double math funcs, no blocklisting or fixups */
+/* defined for legacy reasons, should be deprecated at some point */
+#define npy_sinhl sinhl
+#define npy_coshl coshl
+#define npy_tanhl tanhl
+#define npy_fabsl fabsl
+#define npy_floorl floorl
+#define npy_ceill ceill
+#define npy_rintl rintl
+#define npy_truncl truncl
+#define npy_cbrtl cbrtl
+#define npy_log10l log10l
+#define npy_logl logl
+#define npy_expm1l expm1l
+#define npy_asinl asinl
+#define npy_acosl acosl
+#define npy_atanl atanl
+#define npy_asinhl asinhl
+#define npy_acoshl acoshl
+#define npy_atanhl atanhl
+#define npy_log1pl log1pl
+#define npy_exp2l exp2l
+#define npy_fmodl fmodl
+#define npy_frexpl frexpl
+#define npy_ldexpl ldexpl
+#define npy_copysignl copysignl
+#define npy_nextafterl nextafterl
+
+npy_longdouble npy_spacingl(npy_longdouble x);
+
+/*
+ * Non standard functions
+ */
+NPY_INPLACE double npy_deg2rad(double x);
+NPY_INPLACE double npy_rad2deg(double x);
+NPY_INPLACE double npy_logaddexp(double x, double y);
+NPY_INPLACE double npy_logaddexp2(double x, double y);
+NPY_INPLACE double npy_divmod(double x, double y, double *modulus);
+NPY_INPLACE double npy_heaviside(double x, double h0);
+
+NPY_INPLACE float npy_deg2radf(float x);
+NPY_INPLACE float npy_rad2degf(float x);
+NPY_INPLACE float npy_logaddexpf(float x, float y);
+NPY_INPLACE float npy_logaddexp2f(float x, float y);
+NPY_INPLACE float npy_divmodf(float x, float y, float *modulus);
+NPY_INPLACE float npy_heavisidef(float x, float h0);
+
+NPY_INPLACE npy_longdouble npy_deg2radl(npy_longdouble x);
+NPY_INPLACE npy_longdouble npy_rad2degl(npy_longdouble x);
+NPY_INPLACE npy_longdouble npy_logaddexpl(npy_longdouble x, npy_longdouble y);
+NPY_INPLACE npy_longdouble npy_logaddexp2l(npy_longdouble x, npy_longdouble y);
+NPY_INPLACE npy_longdouble npy_divmodl(npy_longdouble x, npy_longdouble y,
+ npy_longdouble *modulus);
+NPY_INPLACE npy_longdouble npy_heavisidel(npy_longdouble x, npy_longdouble h0);
+
+#define npy_degrees npy_rad2deg
+#define npy_degreesf npy_rad2degf
+#define npy_degreesl npy_rad2degl
+
+#define npy_radians npy_deg2rad
+#define npy_radiansf npy_deg2radf
+#define npy_radiansl npy_deg2radl
+
+/*
+ * Complex declarations
+ */
+
+static inline double npy_creal(const npy_cdouble z)
+{
+#if defined(__cplusplus)
+ return z._Val[0];
+#else
+ return creal(z);
+#endif
+}
+
+static inline void npy_csetreal(npy_cdouble *z, const double r)
+{
+ ((double *) z)[0] = r;
+}
+
+static inline double npy_cimag(const npy_cdouble z)
+{
+#if defined(__cplusplus)
+ return z._Val[1];
+#else
+ return cimag(z);
+#endif
+}
+
+static inline void npy_csetimag(npy_cdouble *z, const double i)
+{
+ ((double *) z)[1] = i;
+}
+
+static inline float npy_crealf(const npy_cfloat z)
+{
+#if defined(__cplusplus)
+ return z._Val[0];
+#else
+ return crealf(z);
+#endif
+}
+
+static inline void npy_csetrealf(npy_cfloat *z, const float r)
+{
+ ((float *) z)[0] = r;
+}
+
+static inline float npy_cimagf(const npy_cfloat z)
+{
+#if defined(__cplusplus)
+ return z._Val[1];
+#else
+ return cimagf(z);
+#endif
+}
+
+static inline void npy_csetimagf(npy_cfloat *z, const float i)
+{
+ ((float *) z)[1] = i;
+}
+
+static inline npy_longdouble npy_creall(const npy_clongdouble z)
+{
+#if defined(__cplusplus)
+ return (npy_longdouble)z._Val[0];
+#else
+ return creall(z);
+#endif
+}
+
+static inline void npy_csetreall(npy_clongdouble *z, const longdouble_t r)
+{
+ ((longdouble_t *) z)[0] = r;
+}
+
+static inline npy_longdouble npy_cimagl(const npy_clongdouble z)
+{
+#if defined(__cplusplus)
+ return (npy_longdouble)z._Val[1];
+#else
+ return cimagl(z);
+#endif
+}
+
+static inline void npy_csetimagl(npy_clongdouble *z, const longdouble_t i)
+{
+ ((longdouble_t *) z)[1] = i;
+}
+
+#define NPY_CSETREAL(z, r) npy_csetreal(z, r)
+#define NPY_CSETIMAG(z, i) npy_csetimag(z, i)
+#define NPY_CSETREALF(z, r) npy_csetrealf(z, r)
+#define NPY_CSETIMAGF(z, i) npy_csetimagf(z, i)
+#define NPY_CSETREALL(z, r) npy_csetreall(z, r)
+#define NPY_CSETIMAGL(z, i) npy_csetimagl(z, i)
+
+static inline npy_cdouble npy_cpack(double x, double y)
+{
+ npy_cdouble z;
+ npy_csetreal(&z, x);
+ npy_csetimag(&z, y);
+ return z;
+}
+
+static inline npy_cfloat npy_cpackf(float x, float y)
+{
+ npy_cfloat z;
+ npy_csetrealf(&z, x);
+ npy_csetimagf(&z, y);
+ return z;
+}
+
+static inline npy_clongdouble npy_cpackl(npy_longdouble x, npy_longdouble y)
+{
+ npy_clongdouble z;
+ npy_csetreall(&z, x);
+ npy_csetimagl(&z, y);
+ return z;
+}
+
+/*
+ * Double precision complex functions
+ */
+double npy_cabs(npy_cdouble z);
+double npy_carg(npy_cdouble z);
+
+npy_cdouble npy_cexp(npy_cdouble z);
+npy_cdouble npy_clog(npy_cdouble z);
+npy_cdouble npy_cpow(npy_cdouble x, npy_cdouble y);
+
+npy_cdouble npy_csqrt(npy_cdouble z);
+
+npy_cdouble npy_ccos(npy_cdouble z);
+npy_cdouble npy_csin(npy_cdouble z);
+npy_cdouble npy_ctan(npy_cdouble z);
+
+npy_cdouble npy_ccosh(npy_cdouble z);
+npy_cdouble npy_csinh(npy_cdouble z);
+npy_cdouble npy_ctanh(npy_cdouble z);
+
+npy_cdouble npy_cacos(npy_cdouble z);
+npy_cdouble npy_casin(npy_cdouble z);
+npy_cdouble npy_catan(npy_cdouble z);
+
+npy_cdouble npy_cacosh(npy_cdouble z);
+npy_cdouble npy_casinh(npy_cdouble z);
+npy_cdouble npy_catanh(npy_cdouble z);
+
+/*
+ * Single precision complex functions
+ */
+float npy_cabsf(npy_cfloat z);
+float npy_cargf(npy_cfloat z);
+
+npy_cfloat npy_cexpf(npy_cfloat z);
+npy_cfloat npy_clogf(npy_cfloat z);
+npy_cfloat npy_cpowf(npy_cfloat x, npy_cfloat y);
+
+npy_cfloat npy_csqrtf(npy_cfloat z);
+
+npy_cfloat npy_ccosf(npy_cfloat z);
+npy_cfloat npy_csinf(npy_cfloat z);
+npy_cfloat npy_ctanf(npy_cfloat z);
+
+npy_cfloat npy_ccoshf(npy_cfloat z);
+npy_cfloat npy_csinhf(npy_cfloat z);
+npy_cfloat npy_ctanhf(npy_cfloat z);
+
+npy_cfloat npy_cacosf(npy_cfloat z);
+npy_cfloat npy_casinf(npy_cfloat z);
+npy_cfloat npy_catanf(npy_cfloat z);
+
+npy_cfloat npy_cacoshf(npy_cfloat z);
+npy_cfloat npy_casinhf(npy_cfloat z);
+npy_cfloat npy_catanhf(npy_cfloat z);
+
+
+/*
+ * Extended precision complex functions
+ */
+npy_longdouble npy_cabsl(npy_clongdouble z);
+npy_longdouble npy_cargl(npy_clongdouble z);
+
+npy_clongdouble npy_cexpl(npy_clongdouble z);
+npy_clongdouble npy_clogl(npy_clongdouble z);
+npy_clongdouble npy_cpowl(npy_clongdouble x, npy_clongdouble y);
+
+npy_clongdouble npy_csqrtl(npy_clongdouble z);
+
+npy_clongdouble npy_ccosl(npy_clongdouble z);
+npy_clongdouble npy_csinl(npy_clongdouble z);
+npy_clongdouble npy_ctanl(npy_clongdouble z);
+
+npy_clongdouble npy_ccoshl(npy_clongdouble z);
+npy_clongdouble npy_csinhl(npy_clongdouble z);
+npy_clongdouble npy_ctanhl(npy_clongdouble z);
+
+npy_clongdouble npy_cacosl(npy_clongdouble z);
+npy_clongdouble npy_casinl(npy_clongdouble z);
+npy_clongdouble npy_catanl(npy_clongdouble z);
+
+npy_clongdouble npy_cacoshl(npy_clongdouble z);
+npy_clongdouble npy_casinhl(npy_clongdouble z);
+npy_clongdouble npy_catanhl(npy_clongdouble z);
+
+
+/*
+ * Functions that set the floating point error
+ * status word.
+ */
+
+/*
+ * platform-dependent code translates floating point
+ * status to an integer sum of these values
+ */
+#define NPY_FPE_DIVIDEBYZERO 1
+#define NPY_FPE_OVERFLOW 2
+#define NPY_FPE_UNDERFLOW 4
+#define NPY_FPE_INVALID 8
+
+int npy_clear_floatstatus_barrier(char*);
+int npy_get_floatstatus_barrier(char*);
+/*
+ * use caution with these - clang and gcc8.1 are known to reorder calls
+ * to this form of the function which can defeat the check. The _barrier
+ * form of the call is preferable, where the argument is
+ * (char*)&local_variable
+ */
+int npy_clear_floatstatus(void);
+int npy_get_floatstatus(void);
+
+void npy_set_floatstatus_divbyzero(void);
+void npy_set_floatstatus_overflow(void);
+void npy_set_floatstatus_underflow(void);
+void npy_set_floatstatus_invalid(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#if NPY_INLINE_MATH
+#include "npy_math_internal.h"
+#endif
+
+#endif /* NUMPY_CORE_INCLUDE_NUMPY_NPY_MATH_H_ */
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/npy_no_deprecated_api.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/npy_no_deprecated_api.h
new file mode 100644
index 0000000000000000000000000000000000000000..39658c0bd2d61aacd25f75439e81ea16c3e33db8
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/npy_no_deprecated_api.h
@@ -0,0 +1,20 @@
+/*
+ * This include file is provided for inclusion in Cython *.pyd files where
+ * one would like to define the NPY_NO_DEPRECATED_API macro. It can be
+ * included by
+ *
+ * cdef extern from "npy_no_deprecated_api.h": pass
+ *
+ */
+#ifndef NPY_NO_DEPRECATED_API
+
+/* put this check here since there may be multiple includes in C extensions. */
+#if defined(NUMPY_CORE_INCLUDE_NUMPY_NDARRAYTYPES_H_) || \
+ defined(NUMPY_CORE_INCLUDE_NUMPY_NPY_DEPRECATED_API_H) || \
+ defined(NUMPY_CORE_INCLUDE_NUMPY_OLD_DEFINES_H_)
+#error "npy_no_deprecated_api.h" must be first among numpy includes.
+#else
+#define NPY_NO_DEPRECATED_API NPY_API_VERSION
+#endif
+
+#endif /* NPY_NO_DEPRECATED_API */
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/npy_os.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/npy_os.h
new file mode 100644
index 0000000000000000000000000000000000000000..0ce5d78b42c0e53c660654e297446d7811901aa2
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/npy_os.h
@@ -0,0 +1,42 @@
+#ifndef NUMPY_CORE_INCLUDE_NUMPY_NPY_OS_H_
+#define NUMPY_CORE_INCLUDE_NUMPY_NPY_OS_H_
+
+#if defined(linux) || defined(__linux) || defined(__linux__)
+ #define NPY_OS_LINUX
+#elif defined(__FreeBSD__) || defined(__NetBSD__) || \
+ defined(__OpenBSD__) || defined(__DragonFly__)
+ #define NPY_OS_BSD
+ #ifdef __FreeBSD__
+ #define NPY_OS_FREEBSD
+ #elif defined(__NetBSD__)
+ #define NPY_OS_NETBSD
+ #elif defined(__OpenBSD__)
+ #define NPY_OS_OPENBSD
+ #elif defined(__DragonFly__)
+ #define NPY_OS_DRAGONFLY
+ #endif
+#elif defined(sun) || defined(__sun)
+ #define NPY_OS_SOLARIS
+#elif defined(__CYGWIN__)
+ #define NPY_OS_CYGWIN
+/* We are on Windows.*/
+#elif defined(_WIN32)
+ /* We are using MinGW (64-bit or 32-bit)*/
+ #if defined(__MINGW32__) || defined(__MINGW64__)
+ #define NPY_OS_MINGW
+ /* Otherwise, if _WIN64 is defined, we are targeting 64-bit Windows*/
+ #elif defined(_WIN64)
+ #define NPY_OS_WIN64
+ /* Otherwise assume we are targeting 32-bit Windows*/
+ #else
+ #define NPY_OS_WIN32
+ #endif
+#elif defined(__APPLE__)
+ #define NPY_OS_DARWIN
+#elif defined(__HAIKU__)
+ #define NPY_OS_HAIKU
+#else
+ #define NPY_OS_UNKNOWN
+#endif
+
+#endif /* NUMPY_CORE_INCLUDE_NUMPY_NPY_OS_H_ */
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/numpyconfig.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/numpyconfig.h
new file mode 100644
index 0000000000000000000000000000000000000000..46ecade41ada08fad4c1ae389cc4e9b6e902de24
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/numpyconfig.h
@@ -0,0 +1,178 @@
+#ifndef NUMPY_CORE_INCLUDE_NUMPY_NPY_NUMPYCONFIG_H_
+#define NUMPY_CORE_INCLUDE_NUMPY_NPY_NUMPYCONFIG_H_
+
+#include "_numpyconfig.h"
+
+/*
+ * On Mac OS X, because there is only one configuration stage for all the archs
+ * in universal builds, any macro which depends on the arch needs to be
+ * hardcoded.
+ *
+ * Note that distutils/pip will attempt a universal2 build when Python itself
+ * is built as universal2, hence this hardcoding is needed even if we do not
+ * support universal2 wheels anymore (see gh-22796).
+ * This code block can be removed after we have dropped the setup.py based
+ * build completely.
+ */
+#ifdef __APPLE__
+ #undef NPY_SIZEOF_LONG
+
+ #ifdef __LP64__
+ #define NPY_SIZEOF_LONG 8
+ #else
+ #define NPY_SIZEOF_LONG 4
+ #endif
+
+ #undef NPY_SIZEOF_LONGDOUBLE
+ #undef NPY_SIZEOF_COMPLEX_LONGDOUBLE
+ #ifdef HAVE_LDOUBLE_IEEE_DOUBLE_LE
+ #undef HAVE_LDOUBLE_IEEE_DOUBLE_LE
+ #endif
+ #ifdef HAVE_LDOUBLE_INTEL_EXTENDED_16_BYTES_LE
+ #undef HAVE_LDOUBLE_INTEL_EXTENDED_16_BYTES_LE
+ #endif
+
+ #if defined(__arm64__)
+ #define NPY_SIZEOF_LONGDOUBLE 8
+ #define NPY_SIZEOF_COMPLEX_LONGDOUBLE 16
+ #define HAVE_LDOUBLE_IEEE_DOUBLE_LE 1
+ #elif defined(__x86_64)
+ #define NPY_SIZEOF_LONGDOUBLE 16
+ #define NPY_SIZEOF_COMPLEX_LONGDOUBLE 32
+ #define HAVE_LDOUBLE_INTEL_EXTENDED_16_BYTES_LE 1
+ #elif defined (__i386)
+ #define NPY_SIZEOF_LONGDOUBLE 12
+ #define NPY_SIZEOF_COMPLEX_LONGDOUBLE 24
+ #elif defined(__ppc__) || defined (__ppc64__)
+ #define NPY_SIZEOF_LONGDOUBLE 16
+ #define NPY_SIZEOF_COMPLEX_LONGDOUBLE 32
+ #else
+ #error "unknown architecture"
+ #endif
+#endif
+
+
+/**
+ * To help with both NPY_TARGET_VERSION and the NPY_NO_DEPRECATED_API macro,
+ * we include API version numbers for specific versions of NumPy.
+ * To exclude all API that was deprecated as of 1.7, add the following before
+ * #including any NumPy headers:
+ * #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
+ * The same is true for NPY_TARGET_VERSION, although NumPy will default to
+ * a backwards compatible build anyway.
+ */
+#define NPY_1_7_API_VERSION 0x00000007
+#define NPY_1_8_API_VERSION 0x00000008
+#define NPY_1_9_API_VERSION 0x00000009
+#define NPY_1_10_API_VERSION 0x0000000a
+#define NPY_1_11_API_VERSION 0x0000000a
+#define NPY_1_12_API_VERSION 0x0000000a
+#define NPY_1_13_API_VERSION 0x0000000b
+#define NPY_1_14_API_VERSION 0x0000000c
+#define NPY_1_15_API_VERSION 0x0000000c
+#define NPY_1_16_API_VERSION 0x0000000d
+#define NPY_1_17_API_VERSION 0x0000000d
+#define NPY_1_18_API_VERSION 0x0000000d
+#define NPY_1_19_API_VERSION 0x0000000d
+#define NPY_1_20_API_VERSION 0x0000000e
+#define NPY_1_21_API_VERSION 0x0000000e
+#define NPY_1_22_API_VERSION 0x0000000f
+#define NPY_1_23_API_VERSION 0x00000010
+#define NPY_1_24_API_VERSION 0x00000010
+#define NPY_1_25_API_VERSION 0x00000011
+#define NPY_2_0_API_VERSION 0x00000012
+#define NPY_2_1_API_VERSION 0x00000013
+
+
+/*
+ * Binary compatibility version number. This number is increased
+ * whenever the C-API is changed such that binary compatibility is
+ * broken, i.e. whenever a recompile of extension modules is needed.
+ */
+#define NPY_VERSION NPY_ABI_VERSION
+
+/*
+ * Minor API version we are compiling to be compatible with. The version
+ * Number is always increased when the API changes via: `NPY_API_VERSION`
+ * (and should maybe just track the NumPy version).
+ *
+ * If we have an internal build, we always target the current version of
+ * course.
+ *
+ * For downstream users, we default to an older version to provide them with
+ * maximum compatibility by default. Downstream can choose to extend that
+ * default, or narrow it down if they wish to use newer API. If you adjust
+ * this, consider the Python version support (example for 1.25.x):
+ *
+ * NumPy 1.25.x supports Python: 3.9 3.10 3.11 (3.12)
+ * NumPy 1.19.x supports Python: 3.6 3.7 3.8 3.9
+ * NumPy 1.17.x supports Python: 3.5 3.6 3.7 3.8
+ * NumPy 1.15.x supports Python: ... 3.6 3.7
+ *
+ * Users of the stable ABI may wish to target the last Python that is not
+ * end of life. This would be 3.8 at NumPy 1.25 release time.
+ * 1.17 as default was the choice of oldest-support-numpy at the time and
+ * has in practice no limit (compared to 1.19). Even earlier becomes legacy.
+ */
+#if defined(NPY_INTERNAL_BUILD) && NPY_INTERNAL_BUILD
+ /* NumPy internal build, always use current version. */
+ #define NPY_FEATURE_VERSION NPY_API_VERSION
+#elif defined(NPY_TARGET_VERSION) && NPY_TARGET_VERSION
+ /* user provided a target version, use it */
+ #define NPY_FEATURE_VERSION NPY_TARGET_VERSION
+#else
+ /* Use the default (increase when dropping Python 3.10 support) */
+ #define NPY_FEATURE_VERSION NPY_1_21_API_VERSION
+#endif
+
+/* Sanity check the (requested) feature version */
+#if NPY_FEATURE_VERSION > NPY_API_VERSION
+ #error "NPY_TARGET_VERSION higher than NumPy headers!"
+#elif NPY_FEATURE_VERSION < NPY_1_15_API_VERSION
+ /* No support for irrelevant old targets, no need for error, but warn. */
+ #ifndef _MSC_VER
+ #warning "Requested NumPy target lower than supported NumPy 1.15."
+ #else
+ #define _WARN___STR2__(x) #x
+ #define _WARN___STR1__(x) _WARN___STR2__(x)
+ #define _WARN___LOC__ __FILE__ "(" _WARN___STR1__(__LINE__) ") : Warning Msg: "
+ #pragma message(_WARN___LOC__"Requested NumPy target lower than supported NumPy 1.15.")
+ #endif
+#endif
+
+/*
+ * We define a human readable translation to the Python version of NumPy
+ * for error messages (and also to allow grepping the binaries for conda).
+ */
+#if NPY_FEATURE_VERSION == NPY_1_7_API_VERSION
+ #define NPY_FEATURE_VERSION_STRING "1.7"
+#elif NPY_FEATURE_VERSION == NPY_1_8_API_VERSION
+ #define NPY_FEATURE_VERSION_STRING "1.8"
+#elif NPY_FEATURE_VERSION == NPY_1_9_API_VERSION
+ #define NPY_FEATURE_VERSION_STRING "1.9"
+#elif NPY_FEATURE_VERSION == NPY_1_10_API_VERSION /* also 1.11, 1.12 */
+ #define NPY_FEATURE_VERSION_STRING "1.10"
+#elif NPY_FEATURE_VERSION == NPY_1_13_API_VERSION
+ #define NPY_FEATURE_VERSION_STRING "1.13"
+#elif NPY_FEATURE_VERSION == NPY_1_14_API_VERSION /* also 1.15 */
+ #define NPY_FEATURE_VERSION_STRING "1.14"
+#elif NPY_FEATURE_VERSION == NPY_1_16_API_VERSION /* also 1.17, 1.18, 1.19 */
+ #define NPY_FEATURE_VERSION_STRING "1.16"
+#elif NPY_FEATURE_VERSION == NPY_1_20_API_VERSION /* also 1.21 */
+ #define NPY_FEATURE_VERSION_STRING "1.20"
+#elif NPY_FEATURE_VERSION == NPY_1_22_API_VERSION
+ #define NPY_FEATURE_VERSION_STRING "1.22"
+#elif NPY_FEATURE_VERSION == NPY_1_23_API_VERSION /* also 1.24 */
+ #define NPY_FEATURE_VERSION_STRING "1.23"
+#elif NPY_FEATURE_VERSION == NPY_1_25_API_VERSION
+ #define NPY_FEATURE_VERSION_STRING "1.25"
+#elif NPY_FEATURE_VERSION == NPY_2_0_API_VERSION
+ #define NPY_FEATURE_VERSION_STRING "2.0"
+#elif NPY_FEATURE_VERSION == NPY_2_1_API_VERSION
+ #define NPY_FEATURE_VERSION_STRING "2.1"
+#else
+ #error "Missing version string define for new NumPy version."
+#endif
+
+
+#endif /* NUMPY_CORE_INCLUDE_NUMPY_NPY_NUMPYCONFIG_H_ */
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/random/LICENSE.txt b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/random/LICENSE.txt
new file mode 100644
index 0000000000000000000000000000000000000000..d72a7c388d406191f2b3113efa5f89916a39d9b2
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/random/LICENSE.txt
@@ -0,0 +1,21 @@
+ zlib License
+ ------------
+
+ Copyright (C) 2010 - 2019 ridiculous_fish,
+ Copyright (C) 2016 - 2019 Kim Walisch,
+
+ This software is provided 'as-is', without any express or implied
+ warranty. In no event will the authors be held liable for any damages
+ arising from the use of this software.
+
+ Permission is granted to anyone to use this software for any purpose,
+ including commercial applications, and to alter it and redistribute it
+ freely, subject to the following restrictions:
+
+ 1. The origin of this software must not be misrepresented; you must not
+ claim that you wrote the original software. If you use this software
+ in a product, an acknowledgment in the product documentation would be
+ appreciated but is not required.
+ 2. Altered source versions must be plainly marked as such, and must not be
+ misrepresented as being the original software.
+ 3. This notice may not be removed or altered from any source distribution.
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/random/bitgen.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/random/bitgen.h
new file mode 100644
index 0000000000000000000000000000000000000000..162dd5c5753079eb1d76efa7fc8a3847c2ad6602
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/random/bitgen.h
@@ -0,0 +1,20 @@
+#ifndef NUMPY_CORE_INCLUDE_NUMPY_RANDOM_BITGEN_H_
+#define NUMPY_CORE_INCLUDE_NUMPY_RANDOM_BITGEN_H_
+
+#pragma once
+#include
+#include
+#include
+
+/* Must match the declaration in numpy/random/.pxd */
+
+typedef struct bitgen {
+ void *state;
+ uint64_t (*next_uint64)(void *st);
+ uint32_t (*next_uint32)(void *st);
+ double (*next_double)(void *st);
+ uint64_t (*next_raw)(void *st);
+} bitgen_t;
+
+
+#endif /* NUMPY_CORE_INCLUDE_NUMPY_RANDOM_BITGEN_H_ */
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/random/distributions.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/random/distributions.h
new file mode 100644
index 0000000000000000000000000000000000000000..e7fa4bd00d43430eb1da23bd577688d8733bb6e8
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/random/distributions.h
@@ -0,0 +1,209 @@
+#ifndef NUMPY_CORE_INCLUDE_NUMPY_RANDOM_DISTRIBUTIONS_H_
+#define NUMPY_CORE_INCLUDE_NUMPY_RANDOM_DISTRIBUTIONS_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include
+#include "numpy/npy_common.h"
+#include
+#include
+#include
+
+#include "numpy/npy_math.h"
+#include "numpy/random/bitgen.h"
+
+/*
+ * RAND_INT_TYPE is used to share integer generators with RandomState which
+ * used long in place of int64_t. If changing a distribution that uses
+ * RAND_INT_TYPE, then the original unmodified copy must be retained for
+ * use in RandomState by copying to the legacy distributions source file.
+ */
+#ifdef NP_RANDOM_LEGACY
+#define RAND_INT_TYPE long
+#define RAND_INT_MAX LONG_MAX
+#else
+#define RAND_INT_TYPE int64_t
+#define RAND_INT_MAX INT64_MAX
+#endif
+
+#ifdef _MSC_VER
+#define DECLDIR __declspec(dllexport)
+#else
+#define DECLDIR extern
+#endif
+
+#ifndef MIN
+#define MIN(x, y) (((x) < (y)) ? x : y)
+#define MAX(x, y) (((x) > (y)) ? x : y)
+#endif
+
+#ifndef M_PI
+#define M_PI 3.14159265358979323846264338328
+#endif
+
+typedef struct s_binomial_t {
+ int has_binomial; /* !=0: following parameters initialized for binomial */
+ double psave;
+ RAND_INT_TYPE nsave;
+ double r;
+ double q;
+ double fm;
+ RAND_INT_TYPE m;
+ double p1;
+ double xm;
+ double xl;
+ double xr;
+ double c;
+ double laml;
+ double lamr;
+ double p2;
+ double p3;
+ double p4;
+} binomial_t;
+
+DECLDIR float random_standard_uniform_f(bitgen_t *bitgen_state);
+DECLDIR double random_standard_uniform(bitgen_t *bitgen_state);
+DECLDIR void random_standard_uniform_fill(bitgen_t *, npy_intp, double *);
+DECLDIR void random_standard_uniform_fill_f(bitgen_t *, npy_intp, float *);
+
+DECLDIR int64_t random_positive_int64(bitgen_t *bitgen_state);
+DECLDIR int32_t random_positive_int32(bitgen_t *bitgen_state);
+DECLDIR int64_t random_positive_int(bitgen_t *bitgen_state);
+DECLDIR uint64_t random_uint(bitgen_t *bitgen_state);
+
+DECLDIR double random_standard_exponential(bitgen_t *bitgen_state);
+DECLDIR float random_standard_exponential_f(bitgen_t *bitgen_state);
+DECLDIR void random_standard_exponential_fill(bitgen_t *, npy_intp, double *);
+DECLDIR void random_standard_exponential_fill_f(bitgen_t *, npy_intp, float *);
+DECLDIR void random_standard_exponential_inv_fill(bitgen_t *, npy_intp, double *);
+DECLDIR void random_standard_exponential_inv_fill_f(bitgen_t *, npy_intp, float *);
+
+DECLDIR double random_standard_normal(bitgen_t *bitgen_state);
+DECLDIR float random_standard_normal_f(bitgen_t *bitgen_state);
+DECLDIR void random_standard_normal_fill(bitgen_t *, npy_intp, double *);
+DECLDIR void random_standard_normal_fill_f(bitgen_t *, npy_intp, float *);
+DECLDIR double random_standard_gamma(bitgen_t *bitgen_state, double shape);
+DECLDIR float random_standard_gamma_f(bitgen_t *bitgen_state, float shape);
+
+DECLDIR double random_normal(bitgen_t *bitgen_state, double loc, double scale);
+
+DECLDIR double random_gamma(bitgen_t *bitgen_state, double shape, double scale);
+DECLDIR float random_gamma_f(bitgen_t *bitgen_state, float shape, float scale);
+
+DECLDIR double random_exponential(bitgen_t *bitgen_state, double scale);
+DECLDIR double random_uniform(bitgen_t *bitgen_state, double lower, double range);
+DECLDIR double random_beta(bitgen_t *bitgen_state, double a, double b);
+DECLDIR double random_chisquare(bitgen_t *bitgen_state, double df);
+DECLDIR double random_f(bitgen_t *bitgen_state, double dfnum, double dfden);
+DECLDIR double random_standard_cauchy(bitgen_t *bitgen_state);
+DECLDIR double random_pareto(bitgen_t *bitgen_state, double a);
+DECLDIR double random_weibull(bitgen_t *bitgen_state, double a);
+DECLDIR double random_power(bitgen_t *bitgen_state, double a);
+DECLDIR double random_laplace(bitgen_t *bitgen_state, double loc, double scale);
+DECLDIR double random_gumbel(bitgen_t *bitgen_state, double loc, double scale);
+DECLDIR double random_logistic(bitgen_t *bitgen_state, double loc, double scale);
+DECLDIR double random_lognormal(bitgen_t *bitgen_state, double mean, double sigma);
+DECLDIR double random_rayleigh(bitgen_t *bitgen_state, double mode);
+DECLDIR double random_standard_t(bitgen_t *bitgen_state, double df);
+DECLDIR double random_noncentral_chisquare(bitgen_t *bitgen_state, double df,
+ double nonc);
+DECLDIR double random_noncentral_f(bitgen_t *bitgen_state, double dfnum,
+ double dfden, double nonc);
+DECLDIR double random_wald(bitgen_t *bitgen_state, double mean, double scale);
+DECLDIR double random_vonmises(bitgen_t *bitgen_state, double mu, double kappa);
+DECLDIR double random_triangular(bitgen_t *bitgen_state, double left, double mode,
+ double right);
+
+DECLDIR RAND_INT_TYPE random_poisson(bitgen_t *bitgen_state, double lam);
+DECLDIR RAND_INT_TYPE random_negative_binomial(bitgen_t *bitgen_state, double n,
+ double p);
+
+DECLDIR int64_t random_binomial(bitgen_t *bitgen_state, double p,
+ int64_t n, binomial_t *binomial);
+
+DECLDIR int64_t random_logseries(bitgen_t *bitgen_state, double p);
+DECLDIR int64_t random_geometric(bitgen_t *bitgen_state, double p);
+DECLDIR RAND_INT_TYPE random_geometric_search(bitgen_t *bitgen_state, double p);
+DECLDIR RAND_INT_TYPE random_zipf(bitgen_t *bitgen_state, double a);
+DECLDIR int64_t random_hypergeometric(bitgen_t *bitgen_state,
+ int64_t good, int64_t bad, int64_t sample);
+DECLDIR uint64_t random_interval(bitgen_t *bitgen_state, uint64_t max);
+
+/* Generate random uint64 numbers in closed interval [off, off + rng]. */
+DECLDIR uint64_t random_bounded_uint64(bitgen_t *bitgen_state, uint64_t off,
+ uint64_t rng, uint64_t mask,
+ bool use_masked);
+
+/* Generate random uint32 numbers in closed interval [off, off + rng]. */
+DECLDIR uint32_t random_buffered_bounded_uint32(bitgen_t *bitgen_state,
+ uint32_t off, uint32_t rng,
+ uint32_t mask, bool use_masked,
+ int *bcnt, uint32_t *buf);
+DECLDIR uint16_t random_buffered_bounded_uint16(bitgen_t *bitgen_state,
+ uint16_t off, uint16_t rng,
+ uint16_t mask, bool use_masked,
+ int *bcnt, uint32_t *buf);
+DECLDIR uint8_t random_buffered_bounded_uint8(bitgen_t *bitgen_state, uint8_t off,
+ uint8_t rng, uint8_t mask,
+ bool use_masked, int *bcnt,
+ uint32_t *buf);
+DECLDIR npy_bool random_buffered_bounded_bool(bitgen_t *bitgen_state, npy_bool off,
+ npy_bool rng, npy_bool mask,
+ bool use_masked, int *bcnt,
+ uint32_t *buf);
+
+DECLDIR void random_bounded_uint64_fill(bitgen_t *bitgen_state, uint64_t off,
+ uint64_t rng, npy_intp cnt,
+ bool use_masked, uint64_t *out);
+DECLDIR void random_bounded_uint32_fill(bitgen_t *bitgen_state, uint32_t off,
+ uint32_t rng, npy_intp cnt,
+ bool use_masked, uint32_t *out);
+DECLDIR void random_bounded_uint16_fill(bitgen_t *bitgen_state, uint16_t off,
+ uint16_t rng, npy_intp cnt,
+ bool use_masked, uint16_t *out);
+DECLDIR void random_bounded_uint8_fill(bitgen_t *bitgen_state, uint8_t off,
+ uint8_t rng, npy_intp cnt,
+ bool use_masked, uint8_t *out);
+DECLDIR void random_bounded_bool_fill(bitgen_t *bitgen_state, npy_bool off,
+ npy_bool rng, npy_intp cnt,
+ bool use_masked, npy_bool *out);
+
+DECLDIR void random_multinomial(bitgen_t *bitgen_state, RAND_INT_TYPE n, RAND_INT_TYPE *mnix,
+ double *pix, npy_intp d, binomial_t *binomial);
+
+/* multivariate hypergeometric, "count" method */
+DECLDIR int random_multivariate_hypergeometric_count(bitgen_t *bitgen_state,
+ int64_t total,
+ size_t num_colors, int64_t *colors,
+ int64_t nsample,
+ size_t num_variates, int64_t *variates);
+
+/* multivariate hypergeometric, "marginals" method */
+DECLDIR void random_multivariate_hypergeometric_marginals(bitgen_t *bitgen_state,
+ int64_t total,
+ size_t num_colors, int64_t *colors,
+ int64_t nsample,
+ size_t num_variates, int64_t *variates);
+
+/* Common to legacy-distributions.c and distributions.c but not exported */
+
+RAND_INT_TYPE random_binomial_btpe(bitgen_t *bitgen_state,
+ RAND_INT_TYPE n,
+ double p,
+ binomial_t *binomial);
+RAND_INT_TYPE random_binomial_inversion(bitgen_t *bitgen_state,
+ RAND_INT_TYPE n,
+ double p,
+ binomial_t *binomial);
+double random_loggam(double x);
+static inline double next_double(bitgen_t *bitgen_state) {
+ return bitgen_state->next_double(bitgen_state->state);
+}
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* NUMPY_CORE_INCLUDE_NUMPY_RANDOM_DISTRIBUTIONS_H_ */
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/random/libdivide.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/random/libdivide.h
new file mode 100644
index 0000000000000000000000000000000000000000..f4eb8039b50c21c0977a38ee5f47c8f89307d482
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/random/libdivide.h
@@ -0,0 +1,2079 @@
+// libdivide.h - Optimized integer division
+// https://libdivide.com
+//
+// Copyright (C) 2010 - 2019 ridiculous_fish,
+// Copyright (C) 2016 - 2019 Kim Walisch,
+//
+// libdivide is dual-licensed under the Boost or zlib licenses.
+// You may use libdivide under the terms of either of these.
+// See LICENSE.txt for more details.
+
+#ifndef NUMPY_CORE_INCLUDE_NUMPY_LIBDIVIDE_LIBDIVIDE_H_
+#define NUMPY_CORE_INCLUDE_NUMPY_LIBDIVIDE_LIBDIVIDE_H_
+
+#define LIBDIVIDE_VERSION "3.0"
+#define LIBDIVIDE_VERSION_MAJOR 3
+#define LIBDIVIDE_VERSION_MINOR 0
+
+#include
+
+#if defined(__cplusplus)
+ #include
+ #include
+ #include
+#else
+ #include
+ #include
+#endif
+
+#if defined(LIBDIVIDE_AVX512)
+ #include
+#elif defined(LIBDIVIDE_AVX2)
+ #include
+#elif defined(LIBDIVIDE_SSE2)
+ #include
+#endif
+
+#if defined(_MSC_VER)
+ #include
+ // disable warning C4146: unary minus operator applied
+ // to unsigned type, result still unsigned
+ #pragma warning(disable: 4146)
+ #define LIBDIVIDE_VC
+#endif
+
+#if !defined(__has_builtin)
+ #define __has_builtin(x) 0
+#endif
+
+#if defined(__SIZEOF_INT128__)
+ #define HAS_INT128_T
+ // clang-cl on Windows does not yet support 128-bit division
+ #if !(defined(__clang__) && defined(LIBDIVIDE_VC))
+ #define HAS_INT128_DIV
+ #endif
+#endif
+
+#if defined(__x86_64__) || defined(_M_X64)
+ #define LIBDIVIDE_X86_64
+#endif
+
+#if defined(__i386__)
+ #define LIBDIVIDE_i386
+#endif
+
+#if defined(__GNUC__) || defined(__clang__)
+ #define LIBDIVIDE_GCC_STYLE_ASM
+#endif
+
+#if defined(__cplusplus) || defined(LIBDIVIDE_VC)
+ #define LIBDIVIDE_FUNCTION __FUNCTION__
+#else
+ #define LIBDIVIDE_FUNCTION __func__
+#endif
+
+#define LIBDIVIDE_ERROR(msg) \
+ do { \
+ fprintf(stderr, "libdivide.h:%d: %s(): Error: %s\n", \
+ __LINE__, LIBDIVIDE_FUNCTION, msg); \
+ abort(); \
+ } while (0)
+
+#if defined(LIBDIVIDE_ASSERTIONS_ON)
+ #define LIBDIVIDE_ASSERT(x) \
+ do { \
+ if (!(x)) { \
+ fprintf(stderr, "libdivide.h:%d: %s(): Assertion failed: %s\n", \
+ __LINE__, LIBDIVIDE_FUNCTION, #x); \
+ abort(); \
+ } \
+ } while (0)
+#else
+ #define LIBDIVIDE_ASSERT(x)
+#endif
+
+#ifdef __cplusplus
+namespace libdivide {
+#endif
+
+// pack divider structs to prevent compilers from padding.
+// This reduces memory usage by up to 43% when using a large
+// array of libdivide dividers and improves performance
+// by up to 10% because of reduced memory bandwidth.
+#pragma pack(push, 1)
+
+struct libdivide_u32_t {
+ uint32_t magic;
+ uint8_t more;
+};
+
+struct libdivide_s32_t {
+ int32_t magic;
+ uint8_t more;
+};
+
+struct libdivide_u64_t {
+ uint64_t magic;
+ uint8_t more;
+};
+
+struct libdivide_s64_t {
+ int64_t magic;
+ uint8_t more;
+};
+
+struct libdivide_u32_branchfree_t {
+ uint32_t magic;
+ uint8_t more;
+};
+
+struct libdivide_s32_branchfree_t {
+ int32_t magic;
+ uint8_t more;
+};
+
+struct libdivide_u64_branchfree_t {
+ uint64_t magic;
+ uint8_t more;
+};
+
+struct libdivide_s64_branchfree_t {
+ int64_t magic;
+ uint8_t more;
+};
+
+#pragma pack(pop)
+
+// Explanation of the "more" field:
+//
+// * Bits 0-5 is the shift value (for shift path or mult path).
+// * Bit 6 is the add indicator for mult path.
+// * Bit 7 is set if the divisor is negative. We use bit 7 as the negative
+// divisor indicator so that we can efficiently use sign extension to
+// create a bitmask with all bits set to 1 (if the divisor is negative)
+// or 0 (if the divisor is positive).
+//
+// u32: [0-4] shift value
+// [5] ignored
+// [6] add indicator
+// magic number of 0 indicates shift path
+//
+// s32: [0-4] shift value
+// [5] ignored
+// [6] add indicator
+// [7] indicates negative divisor
+// magic number of 0 indicates shift path
+//
+// u64: [0-5] shift value
+// [6] add indicator
+// magic number of 0 indicates shift path
+//
+// s64: [0-5] shift value
+// [6] add indicator
+// [7] indicates negative divisor
+// magic number of 0 indicates shift path
+//
+// In s32 and s64 branchfree modes, the magic number is negated according to
+// whether the divisor is negated. In branchfree strategy, it is not negated.
+
+enum {
+ LIBDIVIDE_32_SHIFT_MASK = 0x1F,
+ LIBDIVIDE_64_SHIFT_MASK = 0x3F,
+ LIBDIVIDE_ADD_MARKER = 0x40,
+ LIBDIVIDE_NEGATIVE_DIVISOR = 0x80
+};
+
+static inline struct libdivide_s32_t libdivide_s32_gen(int32_t d);
+static inline struct libdivide_u32_t libdivide_u32_gen(uint32_t d);
+static inline struct libdivide_s64_t libdivide_s64_gen(int64_t d);
+static inline struct libdivide_u64_t libdivide_u64_gen(uint64_t d);
+
+static inline struct libdivide_s32_branchfree_t libdivide_s32_branchfree_gen(int32_t d);
+static inline struct libdivide_u32_branchfree_t libdivide_u32_branchfree_gen(uint32_t d);
+static inline struct libdivide_s64_branchfree_t libdivide_s64_branchfree_gen(int64_t d);
+static inline struct libdivide_u64_branchfree_t libdivide_u64_branchfree_gen(uint64_t d);
+
+static inline int32_t libdivide_s32_do(int32_t numer, const struct libdivide_s32_t *denom);
+static inline uint32_t libdivide_u32_do(uint32_t numer, const struct libdivide_u32_t *denom);
+static inline int64_t libdivide_s64_do(int64_t numer, const struct libdivide_s64_t *denom);
+static inline uint64_t libdivide_u64_do(uint64_t numer, const struct libdivide_u64_t *denom);
+
+static inline int32_t libdivide_s32_branchfree_do(int32_t numer, const struct libdivide_s32_branchfree_t *denom);
+static inline uint32_t libdivide_u32_branchfree_do(uint32_t numer, const struct libdivide_u32_branchfree_t *denom);
+static inline int64_t libdivide_s64_branchfree_do(int64_t numer, const struct libdivide_s64_branchfree_t *denom);
+static inline uint64_t libdivide_u64_branchfree_do(uint64_t numer, const struct libdivide_u64_branchfree_t *denom);
+
+static inline int32_t libdivide_s32_recover(const struct libdivide_s32_t *denom);
+static inline uint32_t libdivide_u32_recover(const struct libdivide_u32_t *denom);
+static inline int64_t libdivide_s64_recover(const struct libdivide_s64_t *denom);
+static inline uint64_t libdivide_u64_recover(const struct libdivide_u64_t *denom);
+
+static inline int32_t libdivide_s32_branchfree_recover(const struct libdivide_s32_branchfree_t *denom);
+static inline uint32_t libdivide_u32_branchfree_recover(const struct libdivide_u32_branchfree_t *denom);
+static inline int64_t libdivide_s64_branchfree_recover(const struct libdivide_s64_branchfree_t *denom);
+static inline uint64_t libdivide_u64_branchfree_recover(const struct libdivide_u64_branchfree_t *denom);
+
+//////// Internal Utility Functions
+
+static inline uint32_t libdivide_mullhi_u32(uint32_t x, uint32_t y) {
+ uint64_t xl = x, yl = y;
+ uint64_t rl = xl * yl;
+ return (uint32_t)(rl >> 32);
+}
+
+static inline int32_t libdivide_mullhi_s32(int32_t x, int32_t y) {
+ int64_t xl = x, yl = y;
+ int64_t rl = xl * yl;
+ // needs to be arithmetic shift
+ return (int32_t)(rl >> 32);
+}
+
+static inline uint64_t libdivide_mullhi_u64(uint64_t x, uint64_t y) {
+#if defined(LIBDIVIDE_VC) && \
+ defined(LIBDIVIDE_X86_64)
+ return __umulh(x, y);
+#elif defined(HAS_INT128_T)
+ __uint128_t xl = x, yl = y;
+ __uint128_t rl = xl * yl;
+ return (uint64_t)(rl >> 64);
+#else
+ // full 128 bits are x0 * y0 + (x0 * y1 << 32) + (x1 * y0 << 32) + (x1 * y1 << 64)
+ uint32_t mask = 0xFFFFFFFF;
+ uint32_t x0 = (uint32_t)(x & mask);
+ uint32_t x1 = (uint32_t)(x >> 32);
+ uint32_t y0 = (uint32_t)(y & mask);
+ uint32_t y1 = (uint32_t)(y >> 32);
+ uint32_t x0y0_hi = libdivide_mullhi_u32(x0, y0);
+ uint64_t x0y1 = x0 * (uint64_t)y1;
+ uint64_t x1y0 = x1 * (uint64_t)y0;
+ uint64_t x1y1 = x1 * (uint64_t)y1;
+ uint64_t temp = x1y0 + x0y0_hi;
+ uint64_t temp_lo = temp & mask;
+ uint64_t temp_hi = temp >> 32;
+
+ return x1y1 + temp_hi + ((temp_lo + x0y1) >> 32);
+#endif
+}
+
+static inline int64_t libdivide_mullhi_s64(int64_t x, int64_t y) {
+#if defined(LIBDIVIDE_VC) && \
+ defined(LIBDIVIDE_X86_64)
+ return __mulh(x, y);
+#elif defined(HAS_INT128_T)
+ __int128_t xl = x, yl = y;
+ __int128_t rl = xl * yl;
+ return (int64_t)(rl >> 64);
+#else
+ // full 128 bits are x0 * y0 + (x0 * y1 << 32) + (x1 * y0 << 32) + (x1 * y1 << 64)
+ uint32_t mask = 0xFFFFFFFF;
+ uint32_t x0 = (uint32_t)(x & mask);
+ uint32_t y0 = (uint32_t)(y & mask);
+ int32_t x1 = (int32_t)(x >> 32);
+ int32_t y1 = (int32_t)(y >> 32);
+ uint32_t x0y0_hi = libdivide_mullhi_u32(x0, y0);
+ int64_t t = x1 * (int64_t)y0 + x0y0_hi;
+ int64_t w1 = x0 * (int64_t)y1 + (t & mask);
+
+ return x1 * (int64_t)y1 + (t >> 32) + (w1 >> 32);
+#endif
+}
+
+static inline int32_t libdivide_count_leading_zeros32(uint32_t val) {
+#if defined(__GNUC__) || \
+ __has_builtin(__builtin_clz)
+ // Fast way to count leading zeros
+ return __builtin_clz(val);
+#elif defined(LIBDIVIDE_VC)
+ unsigned long result;
+ if (_BitScanReverse(&result, val)) {
+ return 31 - result;
+ }
+ return 0;
+#else
+ if (val == 0)
+ return 32;
+ int32_t result = 8;
+ uint32_t hi = 0xFFU << 24;
+ while ((val & hi) == 0) {
+ hi >>= 8;
+ result += 8;
+ }
+ while (val & hi) {
+ result -= 1;
+ hi <<= 1;
+ }
+ return result;
+#endif
+}
+
+static inline int32_t libdivide_count_leading_zeros64(uint64_t val) {
+#if defined(__GNUC__) || \
+ __has_builtin(__builtin_clzll)
+ // Fast way to count leading zeros
+ return __builtin_clzll(val);
+#elif defined(LIBDIVIDE_VC) && defined(_WIN64)
+ unsigned long result;
+ if (_BitScanReverse64(&result, val)) {
+ return 63 - result;
+ }
+ return 0;
+#else
+ uint32_t hi = val >> 32;
+ uint32_t lo = val & 0xFFFFFFFF;
+ if (hi != 0) return libdivide_count_leading_zeros32(hi);
+ return 32 + libdivide_count_leading_zeros32(lo);
+#endif
+}
+
+// libdivide_64_div_32_to_32: divides a 64-bit uint {u1, u0} by a 32-bit
+// uint {v}. The result must fit in 32 bits.
+// Returns the quotient directly and the remainder in *r
+static inline uint32_t libdivide_64_div_32_to_32(uint32_t u1, uint32_t u0, uint32_t v, uint32_t *r) {
+#if (defined(LIBDIVIDE_i386) || defined(LIBDIVIDE_X86_64)) && \
+ defined(LIBDIVIDE_GCC_STYLE_ASM)
+ uint32_t result;
+ __asm__("divl %[v]"
+ : "=a"(result), "=d"(*r)
+ : [v] "r"(v), "a"(u0), "d"(u1)
+ );
+ return result;
+#else
+ uint64_t n = ((uint64_t)u1 << 32) | u0;
+ uint32_t result = (uint32_t)(n / v);
+ *r = (uint32_t)(n - result * (uint64_t)v);
+ return result;
+#endif
+}
+
+// libdivide_128_div_64_to_64: divides a 128-bit uint {u1, u0} by a 64-bit
+// uint {v}. The result must fit in 64 bits.
+// Returns the quotient directly and the remainder in *r
+static uint64_t libdivide_128_div_64_to_64(uint64_t u1, uint64_t u0, uint64_t v, uint64_t *r) {
+#if defined(LIBDIVIDE_X86_64) && \
+ defined(LIBDIVIDE_GCC_STYLE_ASM)
+ uint64_t result;
+ __asm__("divq %[v]"
+ : "=a"(result), "=d"(*r)
+ : [v] "r"(v), "a"(u0), "d"(u1)
+ );
+ return result;
+#elif defined(HAS_INT128_T) && \
+ defined(HAS_INT128_DIV)
+ __uint128_t n = ((__uint128_t)u1 << 64) | u0;
+ uint64_t result = (uint64_t)(n / v);
+ *r = (uint64_t)(n - result * (__uint128_t)v);
+ return result;
+#else
+ // Code taken from Hacker's Delight:
+ // http://www.hackersdelight.org/HDcode/divlu.c.
+ // License permits inclusion here per:
+ // http://www.hackersdelight.org/permissions.htm
+
+ const uint64_t b = (1ULL << 32); // Number base (32 bits)
+ uint64_t un1, un0; // Norm. dividend LSD's
+ uint64_t vn1, vn0; // Norm. divisor digits
+ uint64_t q1, q0; // Quotient digits
+ uint64_t un64, un21, un10; // Dividend digit pairs
+ uint64_t rhat; // A remainder
+ int32_t s; // Shift amount for norm
+
+ // If overflow, set rem. to an impossible value,
+ // and return the largest possible quotient
+ if (u1 >= v) {
+ *r = (uint64_t) -1;
+ return (uint64_t) -1;
+ }
+
+ // count leading zeros
+ s = libdivide_count_leading_zeros64(v);
+ if (s > 0) {
+ // Normalize divisor
+ v = v << s;
+ un64 = (u1 << s) | (u0 >> (64 - s));
+ un10 = u0 << s; // Shift dividend left
+ } else {
+ // Avoid undefined behavior of (u0 >> 64).
+ // The behavior is undefined if the right operand is
+ // negative, or greater than or equal to the length
+ // in bits of the promoted left operand.
+ un64 = u1;
+ un10 = u0;
+ }
+
+ // Break divisor up into two 32-bit digits
+ vn1 = v >> 32;
+ vn0 = v & 0xFFFFFFFF;
+
+ // Break right half of dividend into two digits
+ un1 = un10 >> 32;
+ un0 = un10 & 0xFFFFFFFF;
+
+ // Compute the first quotient digit, q1
+ q1 = un64 / vn1;
+ rhat = un64 - q1 * vn1;
+
+ while (q1 >= b || q1 * vn0 > b * rhat + un1) {
+ q1 = q1 - 1;
+ rhat = rhat + vn1;
+ if (rhat >= b)
+ break;
+ }
+
+ // Multiply and subtract
+ un21 = un64 * b + un1 - q1 * v;
+
+ // Compute the second quotient digit
+ q0 = un21 / vn1;
+ rhat = un21 - q0 * vn1;
+
+ while (q0 >= b || q0 * vn0 > b * rhat + un0) {
+ q0 = q0 - 1;
+ rhat = rhat + vn1;
+ if (rhat >= b)
+ break;
+ }
+
+ *r = (un21 * b + un0 - q0 * v) >> s;
+ return q1 * b + q0;
+#endif
+}
+
+// Bitshift a u128 in place, left (signed_shift > 0) or right (signed_shift < 0)
+static inline void libdivide_u128_shift(uint64_t *u1, uint64_t *u0, int32_t signed_shift) {
+ if (signed_shift > 0) {
+ uint32_t shift = signed_shift;
+ *u1 <<= shift;
+ *u1 |= *u0 >> (64 - shift);
+ *u0 <<= shift;
+ }
+ else if (signed_shift < 0) {
+ uint32_t shift = -signed_shift;
+ *u0 >>= shift;
+ *u0 |= *u1 << (64 - shift);
+ *u1 >>= shift;
+ }
+}
+
+// Computes a 128 / 128 -> 64 bit division, with a 128 bit remainder.
+static uint64_t libdivide_128_div_128_to_64(uint64_t u_hi, uint64_t u_lo, uint64_t v_hi, uint64_t v_lo, uint64_t *r_hi, uint64_t *r_lo) {
+#if defined(HAS_INT128_T) && \
+ defined(HAS_INT128_DIV)
+ __uint128_t ufull = u_hi;
+ __uint128_t vfull = v_hi;
+ ufull = (ufull << 64) | u_lo;
+ vfull = (vfull << 64) | v_lo;
+ uint64_t res = (uint64_t)(ufull / vfull);
+ __uint128_t remainder = ufull - (vfull * res);
+ *r_lo = (uint64_t)remainder;
+ *r_hi = (uint64_t)(remainder >> 64);
+ return res;
+#else
+ // Adapted from "Unsigned Doubleword Division" in Hacker's Delight
+ // We want to compute u / v
+ typedef struct { uint64_t hi; uint64_t lo; } u128_t;
+ u128_t u = {u_hi, u_lo};
+ u128_t v = {v_hi, v_lo};
+
+ if (v.hi == 0) {
+ // divisor v is a 64 bit value, so we just need one 128/64 division
+ // Note that we are simpler than Hacker's Delight here, because we know
+ // the quotient fits in 64 bits whereas Hacker's Delight demands a full
+ // 128 bit quotient
+ *r_hi = 0;
+ return libdivide_128_div_64_to_64(u.hi, u.lo, v.lo, r_lo);
+ }
+ // Here v >= 2**64
+ // We know that v.hi != 0, so count leading zeros is OK
+ // We have 0 <= n <= 63
+ uint32_t n = libdivide_count_leading_zeros64(v.hi);
+
+ // Normalize the divisor so its MSB is 1
+ u128_t v1t = v;
+ libdivide_u128_shift(&v1t.hi, &v1t.lo, n);
+ uint64_t v1 = v1t.hi; // i.e. v1 = v1t >> 64
+
+ // To ensure no overflow
+ u128_t u1 = u;
+ libdivide_u128_shift(&u1.hi, &u1.lo, -1);
+
+ // Get quotient from divide unsigned insn.
+ uint64_t rem_ignored;
+ uint64_t q1 = libdivide_128_div_64_to_64(u1.hi, u1.lo, v1, &rem_ignored);
+
+ // Undo normalization and division of u by 2.
+ u128_t q0 = {0, q1};
+ libdivide_u128_shift(&q0.hi, &q0.lo, n);
+ libdivide_u128_shift(&q0.hi, &q0.lo, -63);
+
+ // Make q0 correct or too small by 1
+ // Equivalent to `if (q0 != 0) q0 = q0 - 1;`
+ if (q0.hi != 0 || q0.lo != 0) {
+ q0.hi -= (q0.lo == 0); // borrow
+ q0.lo -= 1;
+ }
+
+ // Now q0 is correct.
+ // Compute q0 * v as q0v
+ // = (q0.hi << 64 + q0.lo) * (v.hi << 64 + v.lo)
+ // = (q0.hi * v.hi << 128) + (q0.hi * v.lo << 64) +
+ // (q0.lo * v.hi << 64) + q0.lo * v.lo)
+ // Each term is 128 bit
+ // High half of full product (upper 128 bits!) are dropped
+ u128_t q0v = {0, 0};
+ q0v.hi = q0.hi*v.lo + q0.lo*v.hi + libdivide_mullhi_u64(q0.lo, v.lo);
+ q0v.lo = q0.lo*v.lo;
+
+ // Compute u - q0v as u_q0v
+ // This is the remainder
+ u128_t u_q0v = u;
+ u_q0v.hi -= q0v.hi + (u.lo < q0v.lo); // second term is borrow
+ u_q0v.lo -= q0v.lo;
+
+ // Check if u_q0v >= v
+ // This checks if our remainder is larger than the divisor
+ if ((u_q0v.hi > v.hi) ||
+ (u_q0v.hi == v.hi && u_q0v.lo >= v.lo)) {
+ // Increment q0
+ q0.lo += 1;
+ q0.hi += (q0.lo == 0); // carry
+
+ // Subtract v from remainder
+ u_q0v.hi -= v.hi + (u_q0v.lo < v.lo);
+ u_q0v.lo -= v.lo;
+ }
+
+ *r_hi = u_q0v.hi;
+ *r_lo = u_q0v.lo;
+
+ LIBDIVIDE_ASSERT(q0.hi == 0);
+ return q0.lo;
+#endif
+}
+
+////////// UINT32
+
+static inline struct libdivide_u32_t libdivide_internal_u32_gen(uint32_t d, int branchfree) {
+ if (d == 0) {
+ LIBDIVIDE_ERROR("divider must be != 0");
+ }
+
+ struct libdivide_u32_t result;
+ uint32_t floor_log_2_d = 31 - libdivide_count_leading_zeros32(d);
+
+ // Power of 2
+ if ((d & (d - 1)) == 0) {
+ // We need to subtract 1 from the shift value in case of an unsigned
+ // branchfree divider because there is a hardcoded right shift by 1
+ // in its division algorithm. Because of this we also need to add back
+ // 1 in its recovery algorithm.
+ result.magic = 0;
+ result.more = (uint8_t)(floor_log_2_d - (branchfree != 0));
+ } else {
+ uint8_t more;
+ uint32_t rem, proposed_m;
+ proposed_m = libdivide_64_div_32_to_32(1U << floor_log_2_d, 0, d, &rem);
+
+ LIBDIVIDE_ASSERT(rem > 0 && rem < d);
+ const uint32_t e = d - rem;
+
+ // This power works if e < 2**floor_log_2_d.
+ if (!branchfree && (e < (1U << floor_log_2_d))) {
+ // This power works
+ more = floor_log_2_d;
+ } else {
+ // We have to use the general 33-bit algorithm. We need to compute
+ // (2**power) / d. However, we already have (2**(power-1))/d and
+ // its remainder. By doubling both, and then correcting the
+ // remainder, we can compute the larger division.
+ // don't care about overflow here - in fact, we expect it
+ proposed_m += proposed_m;
+ const uint32_t twice_rem = rem + rem;
+ if (twice_rem >= d || twice_rem < rem) proposed_m += 1;
+ more = floor_log_2_d | LIBDIVIDE_ADD_MARKER;
+ }
+ result.magic = 1 + proposed_m;
+ result.more = more;
+ // result.more's shift should in general be ceil_log_2_d. But if we
+ // used the smaller power, we subtract one from the shift because we're
+ // using the smaller power. If we're using the larger power, we
+ // subtract one from the shift because it's taken care of by the add
+ // indicator. So floor_log_2_d happens to be correct in both cases.
+ }
+ return result;
+}
+
+struct libdivide_u32_t libdivide_u32_gen(uint32_t d) {
+ return libdivide_internal_u32_gen(d, 0);
+}
+
+struct libdivide_u32_branchfree_t libdivide_u32_branchfree_gen(uint32_t d) {
+ if (d == 1) {
+ LIBDIVIDE_ERROR("branchfree divider must be != 1");
+ }
+ struct libdivide_u32_t tmp = libdivide_internal_u32_gen(d, 1);
+ struct libdivide_u32_branchfree_t ret = {tmp.magic, (uint8_t)(tmp.more & LIBDIVIDE_32_SHIFT_MASK)};
+ return ret;
+}
+
+uint32_t libdivide_u32_do(uint32_t numer, const struct libdivide_u32_t *denom) {
+ uint8_t more = denom->more;
+ if (!denom->magic) {
+ return numer >> more;
+ }
+ else {
+ uint32_t q = libdivide_mullhi_u32(denom->magic, numer);
+ if (more & LIBDIVIDE_ADD_MARKER) {
+ uint32_t t = ((numer - q) >> 1) + q;
+ return t >> (more & LIBDIVIDE_32_SHIFT_MASK);
+ }
+ else {
+ // All upper bits are 0,
+ // don't need to mask them off.
+ return q >> more;
+ }
+ }
+}
+
+uint32_t libdivide_u32_branchfree_do(uint32_t numer, const struct libdivide_u32_branchfree_t *denom) {
+ uint32_t q = libdivide_mullhi_u32(denom->magic, numer);
+ uint32_t t = ((numer - q) >> 1) + q;
+ return t >> denom->more;
+}
+
+uint32_t libdivide_u32_recover(const struct libdivide_u32_t *denom) {
+ uint8_t more = denom->more;
+ uint8_t shift = more & LIBDIVIDE_32_SHIFT_MASK;
+
+ if (!denom->magic) {
+ return 1U << shift;
+ } else if (!(more & LIBDIVIDE_ADD_MARKER)) {
+ // We compute q = n/d = n*m / 2^(32 + shift)
+ // Therefore we have d = 2^(32 + shift) / m
+ // We need to ceil it.
+ // We know d is not a power of 2, so m is not a power of 2,
+ // so we can just add 1 to the floor
+ uint32_t hi_dividend = 1U << shift;
+ uint32_t rem_ignored;
+ return 1 + libdivide_64_div_32_to_32(hi_dividend, 0, denom->magic, &rem_ignored);
+ } else {
+ // Here we wish to compute d = 2^(32+shift+1)/(m+2^32).
+ // Notice (m + 2^32) is a 33 bit number. Use 64 bit division for now
+ // Also note that shift may be as high as 31, so shift + 1 will
+ // overflow. So we have to compute it as 2^(32+shift)/(m+2^32), and
+ // then double the quotient and remainder.
+ uint64_t half_n = 1ULL << (32 + shift);
+ uint64_t d = (1ULL << 32) | denom->magic;
+ // Note that the quotient is guaranteed <= 32 bits, but the remainder
+ // may need 33!
+ uint32_t half_q = (uint32_t)(half_n / d);
+ uint64_t rem = half_n % d;
+ // We computed 2^(32+shift)/(m+2^32)
+ // Need to double it, and then add 1 to the quotient if doubling th
+ // remainder would increase the quotient.
+ // Note that rem<<1 cannot overflow, since rem < d and d is 33 bits
+ uint32_t full_q = half_q + half_q + ((rem<<1) >= d);
+
+ // We rounded down in gen (hence +1)
+ return full_q + 1;
+ }
+}
+
+uint32_t libdivide_u32_branchfree_recover(const struct libdivide_u32_branchfree_t *denom) {
+ uint8_t more = denom->more;
+ uint8_t shift = more & LIBDIVIDE_32_SHIFT_MASK;
+
+ if (!denom->magic) {
+ return 1U << (shift + 1);
+ } else {
+ // Here we wish to compute d = 2^(32+shift+1)/(m+2^32).
+ // Notice (m + 2^32) is a 33 bit number. Use 64 bit division for now
+ // Also note that shift may be as high as 31, so shift + 1 will
+ // overflow. So we have to compute it as 2^(32+shift)/(m+2^32), and
+ // then double the quotient and remainder.
+ uint64_t half_n = 1ULL << (32 + shift);
+ uint64_t d = (1ULL << 32) | denom->magic;
+ // Note that the quotient is guaranteed <= 32 bits, but the remainder
+ // may need 33!
+ uint32_t half_q = (uint32_t)(half_n / d);
+ uint64_t rem = half_n % d;
+ // We computed 2^(32+shift)/(m+2^32)
+ // Need to double it, and then add 1 to the quotient if doubling th
+ // remainder would increase the quotient.
+ // Note that rem<<1 cannot overflow, since rem < d and d is 33 bits
+ uint32_t full_q = half_q + half_q + ((rem<<1) >= d);
+
+ // We rounded down in gen (hence +1)
+ return full_q + 1;
+ }
+}
+
+/////////// UINT64
+
+static inline struct libdivide_u64_t libdivide_internal_u64_gen(uint64_t d, int branchfree) {
+ if (d == 0) {
+ LIBDIVIDE_ERROR("divider must be != 0");
+ }
+
+ struct libdivide_u64_t result;
+ uint32_t floor_log_2_d = 63 - libdivide_count_leading_zeros64(d);
+
+ // Power of 2
+ if ((d & (d - 1)) == 0) {
+ // We need to subtract 1 from the shift value in case of an unsigned
+ // branchfree divider because there is a hardcoded right shift by 1
+ // in its division algorithm. Because of this we also need to add back
+ // 1 in its recovery algorithm.
+ result.magic = 0;
+ result.more = (uint8_t)(floor_log_2_d - (branchfree != 0));
+ } else {
+ uint64_t proposed_m, rem;
+ uint8_t more;
+ // (1 << (64 + floor_log_2_d)) / d
+ proposed_m = libdivide_128_div_64_to_64(1ULL << floor_log_2_d, 0, d, &rem);
+
+ LIBDIVIDE_ASSERT(rem > 0 && rem < d);
+ const uint64_t e = d - rem;
+
+ // This power works if e < 2**floor_log_2_d.
+ if (!branchfree && e < (1ULL << floor_log_2_d)) {
+ // This power works
+ more = floor_log_2_d;
+ } else {
+ // We have to use the general 65-bit algorithm. We need to compute
+ // (2**power) / d. However, we already have (2**(power-1))/d and
+ // its remainder. By doubling both, and then correcting the
+ // remainder, we can compute the larger division.
+ // don't care about overflow here - in fact, we expect it
+ proposed_m += proposed_m;
+ const uint64_t twice_rem = rem + rem;
+ if (twice_rem >= d || twice_rem < rem) proposed_m += 1;
+ more = floor_log_2_d | LIBDIVIDE_ADD_MARKER;
+ }
+ result.magic = 1 + proposed_m;
+ result.more = more;
+ // result.more's shift should in general be ceil_log_2_d. But if we
+ // used the smaller power, we subtract one from the shift because we're
+ // using the smaller power. If we're using the larger power, we
+ // subtract one from the shift because it's taken care of by the add
+ // indicator. So floor_log_2_d happens to be correct in both cases,
+ // which is why we do it outside of the if statement.
+ }
+ return result;
+}
+
+struct libdivide_u64_t libdivide_u64_gen(uint64_t d) {
+ return libdivide_internal_u64_gen(d, 0);
+}
+
+struct libdivide_u64_branchfree_t libdivide_u64_branchfree_gen(uint64_t d) {
+ if (d == 1) {
+ LIBDIVIDE_ERROR("branchfree divider must be != 1");
+ }
+ struct libdivide_u64_t tmp = libdivide_internal_u64_gen(d, 1);
+ struct libdivide_u64_branchfree_t ret = {tmp.magic, (uint8_t)(tmp.more & LIBDIVIDE_64_SHIFT_MASK)};
+ return ret;
+}
+
+uint64_t libdivide_u64_do(uint64_t numer, const struct libdivide_u64_t *denom) {
+ uint8_t more = denom->more;
+ if (!denom->magic) {
+ return numer >> more;
+ }
+ else {
+ uint64_t q = libdivide_mullhi_u64(denom->magic, numer);
+ if (more & LIBDIVIDE_ADD_MARKER) {
+ uint64_t t = ((numer - q) >> 1) + q;
+ return t >> (more & LIBDIVIDE_64_SHIFT_MASK);
+ }
+ else {
+ // All upper bits are 0,
+ // don't need to mask them off.
+ return q >> more;
+ }
+ }
+}
+
+uint64_t libdivide_u64_branchfree_do(uint64_t numer, const struct libdivide_u64_branchfree_t *denom) {
+ uint64_t q = libdivide_mullhi_u64(denom->magic, numer);
+ uint64_t t = ((numer - q) >> 1) + q;
+ return t >> denom->more;
+}
+
+uint64_t libdivide_u64_recover(const struct libdivide_u64_t *denom) {
+ uint8_t more = denom->more;
+ uint8_t shift = more & LIBDIVIDE_64_SHIFT_MASK;
+
+ if (!denom->magic) {
+ return 1ULL << shift;
+ } else if (!(more & LIBDIVIDE_ADD_MARKER)) {
+ // We compute q = n/d = n*m / 2^(64 + shift)
+ // Therefore we have d = 2^(64 + shift) / m
+ // We need to ceil it.
+ // We know d is not a power of 2, so m is not a power of 2,
+ // so we can just add 1 to the floor
+ uint64_t hi_dividend = 1ULL << shift;
+ uint64_t rem_ignored;
+ return 1 + libdivide_128_div_64_to_64(hi_dividend, 0, denom->magic, &rem_ignored);
+ } else {
+ // Here we wish to compute d = 2^(64+shift+1)/(m+2^64).
+ // Notice (m + 2^64) is a 65 bit number. This gets hairy. See
+ // libdivide_u32_recover for more on what we do here.
+ // TODO: do something better than 128 bit math
+
+ // Full n is a (potentially) 129 bit value
+ // half_n is a 128 bit value
+ // Compute the hi half of half_n. Low half is 0.
+ uint64_t half_n_hi = 1ULL << shift, half_n_lo = 0;
+ // d is a 65 bit value. The high bit is always set to 1.
+ const uint64_t d_hi = 1, d_lo = denom->magic;
+ // Note that the quotient is guaranteed <= 64 bits,
+ // but the remainder may need 65!
+ uint64_t r_hi, r_lo;
+ uint64_t half_q = libdivide_128_div_128_to_64(half_n_hi, half_n_lo, d_hi, d_lo, &r_hi, &r_lo);
+ // We computed 2^(64+shift)/(m+2^64)
+ // Double the remainder ('dr') and check if that is larger than d
+ // Note that d is a 65 bit value, so r1 is small and so r1 + r1
+ // cannot overflow
+ uint64_t dr_lo = r_lo + r_lo;
+ uint64_t dr_hi = r_hi + r_hi + (dr_lo < r_lo); // last term is carry
+ int dr_exceeds_d = (dr_hi > d_hi) || (dr_hi == d_hi && dr_lo >= d_lo);
+ uint64_t full_q = half_q + half_q + (dr_exceeds_d ? 1 : 0);
+ return full_q + 1;
+ }
+}
+
+uint64_t libdivide_u64_branchfree_recover(const struct libdivide_u64_branchfree_t *denom) {
+ uint8_t more = denom->more;
+ uint8_t shift = more & LIBDIVIDE_64_SHIFT_MASK;
+
+ if (!denom->magic) {
+ return 1ULL << (shift + 1);
+ } else {
+ // Here we wish to compute d = 2^(64+shift+1)/(m+2^64).
+ // Notice (m + 2^64) is a 65 bit number. This gets hairy. See
+ // libdivide_u32_recover for more on what we do here.
+ // TODO: do something better than 128 bit math
+
+ // Full n is a (potentially) 129 bit value
+ // half_n is a 128 bit value
+ // Compute the hi half of half_n. Low half is 0.
+ uint64_t half_n_hi = 1ULL << shift, half_n_lo = 0;
+ // d is a 65 bit value. The high bit is always set to 1.
+ const uint64_t d_hi = 1, d_lo = denom->magic;
+ // Note that the quotient is guaranteed <= 64 bits,
+ // but the remainder may need 65!
+ uint64_t r_hi, r_lo;
+ uint64_t half_q = libdivide_128_div_128_to_64(half_n_hi, half_n_lo, d_hi, d_lo, &r_hi, &r_lo);
+ // We computed 2^(64+shift)/(m+2^64)
+ // Double the remainder ('dr') and check if that is larger than d
+ // Note that d is a 65 bit value, so r1 is small and so r1 + r1
+ // cannot overflow
+ uint64_t dr_lo = r_lo + r_lo;
+ uint64_t dr_hi = r_hi + r_hi + (dr_lo < r_lo); // last term is carry
+ int dr_exceeds_d = (dr_hi > d_hi) || (dr_hi == d_hi && dr_lo >= d_lo);
+ uint64_t full_q = half_q + half_q + (dr_exceeds_d ? 1 : 0);
+ return full_q + 1;
+ }
+}
+
+/////////// SINT32
+
+static inline struct libdivide_s32_t libdivide_internal_s32_gen(int32_t d, int branchfree) {
+ if (d == 0) {
+ LIBDIVIDE_ERROR("divider must be != 0");
+ }
+
+ struct libdivide_s32_t result;
+
+ // If d is a power of 2, or negative a power of 2, we have to use a shift.
+ // This is especially important because the magic algorithm fails for -1.
+ // To check if d is a power of 2 or its inverse, it suffices to check
+ // whether its absolute value has exactly one bit set. This works even for
+ // INT_MIN, because abs(INT_MIN) == INT_MIN, and INT_MIN has one bit set
+ // and is a power of 2.
+ uint32_t ud = (uint32_t)d;
+ uint32_t absD = (d < 0) ? -ud : ud;
+ uint32_t floor_log_2_d = 31 - libdivide_count_leading_zeros32(absD);
+ // check if exactly one bit is set,
+ // don't care if absD is 0 since that's divide by zero
+ if ((absD & (absD - 1)) == 0) {
+ // Branchfree and normal paths are exactly the same
+ result.magic = 0;
+ result.more = floor_log_2_d | (d < 0 ? LIBDIVIDE_NEGATIVE_DIVISOR : 0);
+ } else {
+ LIBDIVIDE_ASSERT(floor_log_2_d >= 1);
+
+ uint8_t more;
+ // the dividend here is 2**(floor_log_2_d + 31), so the low 32 bit word
+ // is 0 and the high word is floor_log_2_d - 1
+ uint32_t rem, proposed_m;
+ proposed_m = libdivide_64_div_32_to_32(1U << (floor_log_2_d - 1), 0, absD, &rem);
+ const uint32_t e = absD - rem;
+
+ // We are going to start with a power of floor_log_2_d - 1.
+ // This works if works if e < 2**floor_log_2_d.
+ if (!branchfree && e < (1U << floor_log_2_d)) {
+ // This power works
+ more = floor_log_2_d - 1;
+ } else {
+ // We need to go one higher. This should not make proposed_m
+ // overflow, but it will make it negative when interpreted as an
+ // int32_t.
+ proposed_m += proposed_m;
+ const uint32_t twice_rem = rem + rem;
+ if (twice_rem >= absD || twice_rem < rem) proposed_m += 1;
+ more = floor_log_2_d | LIBDIVIDE_ADD_MARKER;
+ }
+
+ proposed_m += 1;
+ int32_t magic = (int32_t)proposed_m;
+
+ // Mark if we are negative. Note we only negate the magic number in the
+ // branchfull case.
+ if (d < 0) {
+ more |= LIBDIVIDE_NEGATIVE_DIVISOR;
+ if (!branchfree) {
+ magic = -magic;
+ }
+ }
+
+ result.more = more;
+ result.magic = magic;
+ }
+ return result;
+}
+
+struct libdivide_s32_t libdivide_s32_gen(int32_t d) {
+ return libdivide_internal_s32_gen(d, 0);
+}
+
+struct libdivide_s32_branchfree_t libdivide_s32_branchfree_gen(int32_t d) {
+ struct libdivide_s32_t tmp = libdivide_internal_s32_gen(d, 1);
+ struct libdivide_s32_branchfree_t result = {tmp.magic, tmp.more};
+ return result;
+}
+
+int32_t libdivide_s32_do(int32_t numer, const struct libdivide_s32_t *denom) {
+ uint8_t more = denom->more;
+ uint8_t shift = more & LIBDIVIDE_32_SHIFT_MASK;
+
+ if (!denom->magic) {
+ uint32_t sign = (int8_t)more >> 7;
+ uint32_t mask = (1U << shift) - 1;
+ uint32_t uq = numer + ((numer >> 31) & mask);
+ int32_t q = (int32_t)uq;
+ q >>= shift;
+ q = (q ^ sign) - sign;
+ return q;
+ } else {
+ uint32_t uq = (uint32_t)libdivide_mullhi_s32(denom->magic, numer);
+ if (more & LIBDIVIDE_ADD_MARKER) {
+ // must be arithmetic shift and then sign extend
+ int32_t sign = (int8_t)more >> 7;
+ // q += (more < 0 ? -numer : numer)
+ // cast required to avoid UB
+ uq += ((uint32_t)numer ^ sign) - sign;
+ }
+ int32_t q = (int32_t)uq;
+ q >>= shift;
+ q += (q < 0);
+ return q;
+ }
+}
+
+int32_t libdivide_s32_branchfree_do(int32_t numer, const struct libdivide_s32_branchfree_t *denom) {
+ uint8_t more = denom->more;
+ uint8_t shift = more & LIBDIVIDE_32_SHIFT_MASK;
+ // must be arithmetic shift and then sign extend
+ int32_t sign = (int8_t)more >> 7;
+ int32_t magic = denom->magic;
+ int32_t q = libdivide_mullhi_s32(magic, numer);
+ q += numer;
+
+ // If q is non-negative, we have nothing to do
+ // If q is negative, we want to add either (2**shift)-1 if d is a power of
+ // 2, or (2**shift) if it is not a power of 2
+ uint32_t is_power_of_2 = (magic == 0);
+ uint32_t q_sign = (uint32_t)(q >> 31);
+ q += q_sign & ((1U << shift) - is_power_of_2);
+
+ // Now arithmetic right shift
+ q >>= shift;
+ // Negate if needed
+ q = (q ^ sign) - sign;
+
+ return q;
+}
+
+int32_t libdivide_s32_recover(const struct libdivide_s32_t *denom) {
+ uint8_t more = denom->more;
+ uint8_t shift = more & LIBDIVIDE_32_SHIFT_MASK;
+ if (!denom->magic) {
+ uint32_t absD = 1U << shift;
+ if (more & LIBDIVIDE_NEGATIVE_DIVISOR) {
+ absD = -absD;
+ }
+ return (int32_t)absD;
+ } else {
+ // Unsigned math is much easier
+ // We negate the magic number only in the branchfull case, and we don't
+ // know which case we're in. However we have enough information to
+ // determine the correct sign of the magic number. The divisor was
+ // negative if LIBDIVIDE_NEGATIVE_DIVISOR is set. If ADD_MARKER is set,
+ // the magic number's sign is opposite that of the divisor.
+ // We want to compute the positive magic number.
+ int negative_divisor = (more & LIBDIVIDE_NEGATIVE_DIVISOR);
+ int magic_was_negated = (more & LIBDIVIDE_ADD_MARKER)
+ ? denom->magic > 0 : denom->magic < 0;
+
+ // Handle the power of 2 case (including branchfree)
+ if (denom->magic == 0) {
+ int32_t result = 1U << shift;
+ return negative_divisor ? -result : result;
+ }
+
+ uint32_t d = (uint32_t)(magic_was_negated ? -denom->magic : denom->magic);
+ uint64_t n = 1ULL << (32 + shift); // this shift cannot exceed 30
+ uint32_t q = (uint32_t)(n / d);
+ int32_t result = (int32_t)q;
+ result += 1;
+ return negative_divisor ? -result : result;
+ }
+}
+
+int32_t libdivide_s32_branchfree_recover(const struct libdivide_s32_branchfree_t *denom) {
+ return libdivide_s32_recover((const struct libdivide_s32_t *)denom);
+}
+
+///////////// SINT64
+
+static inline struct libdivide_s64_t libdivide_internal_s64_gen(int64_t d, int branchfree) {
+ if (d == 0) {
+ LIBDIVIDE_ERROR("divider must be != 0");
+ }
+
+ struct libdivide_s64_t result;
+
+ // If d is a power of 2, or negative a power of 2, we have to use a shift.
+ // This is especially important because the magic algorithm fails for -1.
+ // To check if d is a power of 2 or its inverse, it suffices to check
+ // whether its absolute value has exactly one bit set. This works even for
+ // INT_MIN, because abs(INT_MIN) == INT_MIN, and INT_MIN has one bit set
+ // and is a power of 2.
+ uint64_t ud = (uint64_t)d;
+ uint64_t absD = (d < 0) ? -ud : ud;
+ uint32_t floor_log_2_d = 63 - libdivide_count_leading_zeros64(absD);
+ // check if exactly one bit is set,
+ // don't care if absD is 0 since that's divide by zero
+ if ((absD & (absD - 1)) == 0) {
+ // Branchfree and non-branchfree cases are the same
+ result.magic = 0;
+ result.more = floor_log_2_d | (d < 0 ? LIBDIVIDE_NEGATIVE_DIVISOR : 0);
+ } else {
+ // the dividend here is 2**(floor_log_2_d + 63), so the low 64 bit word
+ // is 0 and the high word is floor_log_2_d - 1
+ uint8_t more;
+ uint64_t rem, proposed_m;
+ proposed_m = libdivide_128_div_64_to_64(1ULL << (floor_log_2_d - 1), 0, absD, &rem);
+ const uint64_t e = absD - rem;
+
+ // We are going to start with a power of floor_log_2_d - 1.
+ // This works if works if e < 2**floor_log_2_d.
+ if (!branchfree && e < (1ULL << floor_log_2_d)) {
+ // This power works
+ more = floor_log_2_d - 1;
+ } else {
+ // We need to go one higher. This should not make proposed_m
+ // overflow, but it will make it negative when interpreted as an
+ // int32_t.
+ proposed_m += proposed_m;
+ const uint64_t twice_rem = rem + rem;
+ if (twice_rem >= absD || twice_rem < rem) proposed_m += 1;
+ // note that we only set the LIBDIVIDE_NEGATIVE_DIVISOR bit if we
+ // also set ADD_MARKER this is an annoying optimization that
+ // enables algorithm #4 to avoid the mask. However we always set it
+ // in the branchfree case
+ more = floor_log_2_d | LIBDIVIDE_ADD_MARKER;
+ }
+ proposed_m += 1;
+ int64_t magic = (int64_t)proposed_m;
+
+ // Mark if we are negative
+ if (d < 0) {
+ more |= LIBDIVIDE_NEGATIVE_DIVISOR;
+ if (!branchfree) {
+ magic = -magic;
+ }
+ }
+
+ result.more = more;
+ result.magic = magic;
+ }
+ return result;
+}
+
+struct libdivide_s64_t libdivide_s64_gen(int64_t d) {
+ return libdivide_internal_s64_gen(d, 0);
+}
+
+struct libdivide_s64_branchfree_t libdivide_s64_branchfree_gen(int64_t d) {
+ struct libdivide_s64_t tmp = libdivide_internal_s64_gen(d, 1);
+ struct libdivide_s64_branchfree_t ret = {tmp.magic, tmp.more};
+ return ret;
+}
+
+int64_t libdivide_s64_do(int64_t numer, const struct libdivide_s64_t *denom) {
+ uint8_t more = denom->more;
+ uint8_t shift = more & LIBDIVIDE_64_SHIFT_MASK;
+
+ if (!denom->magic) { // shift path
+ uint64_t mask = (1ULL << shift) - 1;
+ uint64_t uq = numer + ((numer >> 63) & mask);
+ int64_t q = (int64_t)uq;
+ q >>= shift;
+ // must be arithmetic shift and then sign-extend
+ int64_t sign = (int8_t)more >> 7;
+ q = (q ^ sign) - sign;
+ return q;
+ } else {
+ uint64_t uq = (uint64_t)libdivide_mullhi_s64(denom->magic, numer);
+ if (more & LIBDIVIDE_ADD_MARKER) {
+ // must be arithmetic shift and then sign extend
+ int64_t sign = (int8_t)more >> 7;
+ // q += (more < 0 ? -numer : numer)
+ // cast required to avoid UB
+ uq += ((uint64_t)numer ^ sign) - sign;
+ }
+ int64_t q = (int64_t)uq;
+ q >>= shift;
+ q += (q < 0);
+ return q;
+ }
+}
+
+int64_t libdivide_s64_branchfree_do(int64_t numer, const struct libdivide_s64_branchfree_t *denom) {
+ uint8_t more = denom->more;
+ uint8_t shift = more & LIBDIVIDE_64_SHIFT_MASK;
+ // must be arithmetic shift and then sign extend
+ int64_t sign = (int8_t)more >> 7;
+ int64_t magic = denom->magic;
+ int64_t q = libdivide_mullhi_s64(magic, numer);
+ q += numer;
+
+ // If q is non-negative, we have nothing to do.
+ // If q is negative, we want to add either (2**shift)-1 if d is a power of
+ // 2, or (2**shift) if it is not a power of 2.
+ uint64_t is_power_of_2 = (magic == 0);
+ uint64_t q_sign = (uint64_t)(q >> 63);
+ q += q_sign & ((1ULL << shift) - is_power_of_2);
+
+ // Arithmetic right shift
+ q >>= shift;
+ // Negate if needed
+ q = (q ^ sign) - sign;
+
+ return q;
+}
+
+int64_t libdivide_s64_recover(const struct libdivide_s64_t *denom) {
+ uint8_t more = denom->more;
+ uint8_t shift = more & LIBDIVIDE_64_SHIFT_MASK;
+ if (denom->magic == 0) { // shift path
+ uint64_t absD = 1ULL << shift;
+ if (more & LIBDIVIDE_NEGATIVE_DIVISOR) {
+ absD = -absD;
+ }
+ return (int64_t)absD;
+ } else {
+ // Unsigned math is much easier
+ int negative_divisor = (more & LIBDIVIDE_NEGATIVE_DIVISOR);
+ int magic_was_negated = (more & LIBDIVIDE_ADD_MARKER)
+ ? denom->magic > 0 : denom->magic < 0;
+
+ uint64_t d = (uint64_t)(magic_was_negated ? -denom->magic : denom->magic);
+ uint64_t n_hi = 1ULL << shift, n_lo = 0;
+ uint64_t rem_ignored;
+ uint64_t q = libdivide_128_div_64_to_64(n_hi, n_lo, d, &rem_ignored);
+ int64_t result = (int64_t)(q + 1);
+ if (negative_divisor) {
+ result = -result;
+ }
+ return result;
+ }
+}
+
+int64_t libdivide_s64_branchfree_recover(const struct libdivide_s64_branchfree_t *denom) {
+ return libdivide_s64_recover((const struct libdivide_s64_t *)denom);
+}
+
+#if defined(LIBDIVIDE_AVX512)
+
+static inline __m512i libdivide_u32_do_vector(__m512i numers, const struct libdivide_u32_t *denom);
+static inline __m512i libdivide_s32_do_vector(__m512i numers, const struct libdivide_s32_t *denom);
+static inline __m512i libdivide_u64_do_vector(__m512i numers, const struct libdivide_u64_t *denom);
+static inline __m512i libdivide_s64_do_vector(__m512i numers, const struct libdivide_s64_t *denom);
+
+static inline __m512i libdivide_u32_branchfree_do_vector(__m512i numers, const struct libdivide_u32_branchfree_t *denom);
+static inline __m512i libdivide_s32_branchfree_do_vector(__m512i numers, const struct libdivide_s32_branchfree_t *denom);
+static inline __m512i libdivide_u64_branchfree_do_vector(__m512i numers, const struct libdivide_u64_branchfree_t *denom);
+static inline __m512i libdivide_s64_branchfree_do_vector(__m512i numers, const struct libdivide_s64_branchfree_t *denom);
+
+//////// Internal Utility Functions
+
+static inline __m512i libdivide_s64_signbits(__m512i v) {;
+ return _mm512_srai_epi64(v, 63);
+}
+
+static inline __m512i libdivide_s64_shift_right_vector(__m512i v, int amt) {
+ return _mm512_srai_epi64(v, amt);
+}
+
+// Here, b is assumed to contain one 32-bit value repeated.
+static inline __m512i libdivide_mullhi_u32_vector(__m512i a, __m512i b) {
+ __m512i hi_product_0Z2Z = _mm512_srli_epi64(_mm512_mul_epu32(a, b), 32);
+ __m512i a1X3X = _mm512_srli_epi64(a, 32);
+ __m512i mask = _mm512_set_epi32(-1, 0, -1, 0, -1, 0, -1, 0, -1, 0, -1, 0, -1, 0, -1, 0);
+ __m512i hi_product_Z1Z3 = _mm512_and_si512(_mm512_mul_epu32(a1X3X, b), mask);
+ return _mm512_or_si512(hi_product_0Z2Z, hi_product_Z1Z3);
+}
+
+// b is one 32-bit value repeated.
+static inline __m512i libdivide_mullhi_s32_vector(__m512i a, __m512i b) {
+ __m512i hi_product_0Z2Z = _mm512_srli_epi64(_mm512_mul_epi32(a, b), 32);
+ __m512i a1X3X = _mm512_srli_epi64(a, 32);
+ __m512i mask = _mm512_set_epi32(-1, 0, -1, 0, -1, 0, -1, 0, -1, 0, -1, 0, -1, 0, -1, 0);
+ __m512i hi_product_Z1Z3 = _mm512_and_si512(_mm512_mul_epi32(a1X3X, b), mask);
+ return _mm512_or_si512(hi_product_0Z2Z, hi_product_Z1Z3);
+}
+
+// Here, y is assumed to contain one 64-bit value repeated.
+// https://stackoverflow.com/a/28827013
+static inline __m512i libdivide_mullhi_u64_vector(__m512i x, __m512i y) {
+ __m512i lomask = _mm512_set1_epi64(0xffffffff);
+ __m512i xh = _mm512_shuffle_epi32(x, (_MM_PERM_ENUM) 0xB1);
+ __m512i yh = _mm512_shuffle_epi32(y, (_MM_PERM_ENUM) 0xB1);
+ __m512i w0 = _mm512_mul_epu32(x, y);
+ __m512i w1 = _mm512_mul_epu32(x, yh);
+ __m512i w2 = _mm512_mul_epu32(xh, y);
+ __m512i w3 = _mm512_mul_epu32(xh, yh);
+ __m512i w0h = _mm512_srli_epi64(w0, 32);
+ __m512i s1 = _mm512_add_epi64(w1, w0h);
+ __m512i s1l = _mm512_and_si512(s1, lomask);
+ __m512i s1h = _mm512_srli_epi64(s1, 32);
+ __m512i s2 = _mm512_add_epi64(w2, s1l);
+ __m512i s2h = _mm512_srli_epi64(s2, 32);
+ __m512i hi = _mm512_add_epi64(w3, s1h);
+ hi = _mm512_add_epi64(hi, s2h);
+
+ return hi;
+}
+
+// y is one 64-bit value repeated.
+static inline __m512i libdivide_mullhi_s64_vector(__m512i x, __m512i y) {
+ __m512i p = libdivide_mullhi_u64_vector(x, y);
+ __m512i t1 = _mm512_and_si512(libdivide_s64_signbits(x), y);
+ __m512i t2 = _mm512_and_si512(libdivide_s64_signbits(y), x);
+ p = _mm512_sub_epi64(p, t1);
+ p = _mm512_sub_epi64(p, t2);
+ return p;
+}
+
+////////// UINT32
+
+__m512i libdivide_u32_do_vector(__m512i numers, const struct libdivide_u32_t *denom) {
+ uint8_t more = denom->more;
+ if (!denom->magic) {
+ return _mm512_srli_epi32(numers, more);
+ }
+ else {
+ __m512i q = libdivide_mullhi_u32_vector(numers, _mm512_set1_epi32(denom->magic));
+ if (more & LIBDIVIDE_ADD_MARKER) {
+ // uint32_t t = ((numer - q) >> 1) + q;
+ // return t >> denom->shift;
+ uint32_t shift = more & LIBDIVIDE_32_SHIFT_MASK;
+ __m512i t = _mm512_add_epi32(_mm512_srli_epi32(_mm512_sub_epi32(numers, q), 1), q);
+ return _mm512_srli_epi32(t, shift);
+ }
+ else {
+ return _mm512_srli_epi32(q, more);
+ }
+ }
+}
+
+__m512i libdivide_u32_branchfree_do_vector(__m512i numers, const struct libdivide_u32_branchfree_t *denom) {
+ __m512i q = libdivide_mullhi_u32_vector(numers, _mm512_set1_epi32(denom->magic));
+ __m512i t = _mm512_add_epi32(_mm512_srli_epi32(_mm512_sub_epi32(numers, q), 1), q);
+ return _mm512_srli_epi32(t, denom->more);
+}
+
+////////// UINT64
+
+__m512i libdivide_u64_do_vector(__m512i numers, const struct libdivide_u64_t *denom) {
+ uint8_t more = denom->more;
+ if (!denom->magic) {
+ return _mm512_srli_epi64(numers, more);
+ }
+ else {
+ __m512i q = libdivide_mullhi_u64_vector(numers, _mm512_set1_epi64(denom->magic));
+ if (more & LIBDIVIDE_ADD_MARKER) {
+ // uint32_t t = ((numer - q) >> 1) + q;
+ // return t >> denom->shift;
+ uint32_t shift = more & LIBDIVIDE_64_SHIFT_MASK;
+ __m512i t = _mm512_add_epi64(_mm512_srli_epi64(_mm512_sub_epi64(numers, q), 1), q);
+ return _mm512_srli_epi64(t, shift);
+ }
+ else {
+ return _mm512_srli_epi64(q, more);
+ }
+ }
+}
+
+__m512i libdivide_u64_branchfree_do_vector(__m512i numers, const struct libdivide_u64_branchfree_t *denom) {
+ __m512i q = libdivide_mullhi_u64_vector(numers, _mm512_set1_epi64(denom->magic));
+ __m512i t = _mm512_add_epi64(_mm512_srli_epi64(_mm512_sub_epi64(numers, q), 1), q);
+ return _mm512_srli_epi64(t, denom->more);
+}
+
+////////// SINT32
+
+__m512i libdivide_s32_do_vector(__m512i numers, const struct libdivide_s32_t *denom) {
+ uint8_t more = denom->more;
+ if (!denom->magic) {
+ uint32_t shift = more & LIBDIVIDE_32_SHIFT_MASK;
+ uint32_t mask = (1U << shift) - 1;
+ __m512i roundToZeroTweak = _mm512_set1_epi32(mask);
+ // q = numer + ((numer >> 31) & roundToZeroTweak);
+ __m512i q = _mm512_add_epi32(numers, _mm512_and_si512(_mm512_srai_epi32(numers, 31), roundToZeroTweak));
+ q = _mm512_srai_epi32(q, shift);
+ __m512i sign = _mm512_set1_epi32((int8_t)more >> 7);
+ // q = (q ^ sign) - sign;
+ q = _mm512_sub_epi32(_mm512_xor_si512(q, sign), sign);
+ return q;
+ }
+ else {
+ __m512i q = libdivide_mullhi_s32_vector(numers, _mm512_set1_epi32(denom->magic));
+ if (more & LIBDIVIDE_ADD_MARKER) {
+ // must be arithmetic shift
+ __m512i sign = _mm512_set1_epi32((int8_t)more >> 7);
+ // q += ((numer ^ sign) - sign);
+ q = _mm512_add_epi32(q, _mm512_sub_epi32(_mm512_xor_si512(numers, sign), sign));
+ }
+ // q >>= shift
+ q = _mm512_srai_epi32(q, more & LIBDIVIDE_32_SHIFT_MASK);
+ q = _mm512_add_epi32(q, _mm512_srli_epi32(q, 31)); // q += (q < 0)
+ return q;
+ }
+}
+
+__m512i libdivide_s32_branchfree_do_vector(__m512i numers, const struct libdivide_s32_branchfree_t *denom) {
+ int32_t magic = denom->magic;
+ uint8_t more = denom->more;
+ uint8_t shift = more & LIBDIVIDE_32_SHIFT_MASK;
+ // must be arithmetic shift
+ __m512i sign = _mm512_set1_epi32((int8_t)more >> 7);
+ __m512i q = libdivide_mullhi_s32_vector(numers, _mm512_set1_epi32(magic));
+ q = _mm512_add_epi32(q, numers); // q += numers
+
+ // If q is non-negative, we have nothing to do
+ // If q is negative, we want to add either (2**shift)-1 if d is
+ // a power of 2, or (2**shift) if it is not a power of 2
+ uint32_t is_power_of_2 = (magic == 0);
+ __m512i q_sign = _mm512_srai_epi32(q, 31); // q_sign = q >> 31
+ __m512i mask = _mm512_set1_epi32((1U << shift) - is_power_of_2);
+ q = _mm512_add_epi32(q, _mm512_and_si512(q_sign, mask)); // q = q + (q_sign & mask)
+ q = _mm512_srai_epi32(q, shift); // q >>= shift
+ q = _mm512_sub_epi32(_mm512_xor_si512(q, sign), sign); // q = (q ^ sign) - sign
+ return q;
+}
+
+////////// SINT64
+
+__m512i libdivide_s64_do_vector(__m512i numers, const struct libdivide_s64_t *denom) {
+ uint8_t more = denom->more;
+ int64_t magic = denom->magic;
+ if (magic == 0) { // shift path
+ uint32_t shift = more & LIBDIVIDE_64_SHIFT_MASK;
+ uint64_t mask = (1ULL << shift) - 1;
+ __m512i roundToZeroTweak = _mm512_set1_epi64(mask);
+ // q = numer + ((numer >> 63) & roundToZeroTweak);
+ __m512i q = _mm512_add_epi64(numers, _mm512_and_si512(libdivide_s64_signbits(numers), roundToZeroTweak));
+ q = libdivide_s64_shift_right_vector(q, shift);
+ __m512i sign = _mm512_set1_epi32((int8_t)more >> 7);
+ // q = (q ^ sign) - sign;
+ q = _mm512_sub_epi64(_mm512_xor_si512(q, sign), sign);
+ return q;
+ }
+ else {
+ __m512i q = libdivide_mullhi_s64_vector(numers, _mm512_set1_epi64(magic));
+ if (more & LIBDIVIDE_ADD_MARKER) {
+ // must be arithmetic shift
+ __m512i sign = _mm512_set1_epi32((int8_t)more >> 7);
+ // q += ((numer ^ sign) - sign);
+ q = _mm512_add_epi64(q, _mm512_sub_epi64(_mm512_xor_si512(numers, sign), sign));
+ }
+ // q >>= denom->mult_path.shift
+ q = libdivide_s64_shift_right_vector(q, more & LIBDIVIDE_64_SHIFT_MASK);
+ q = _mm512_add_epi64(q, _mm512_srli_epi64(q, 63)); // q += (q < 0)
+ return q;
+ }
+}
+
+__m512i libdivide_s64_branchfree_do_vector(__m512i numers, const struct libdivide_s64_branchfree_t *denom) {
+ int64_t magic = denom->magic;
+ uint8_t more = denom->more;
+ uint8_t shift = more & LIBDIVIDE_64_SHIFT_MASK;
+ // must be arithmetic shift
+ __m512i sign = _mm512_set1_epi32((int8_t)more >> 7);
+
+ // libdivide_mullhi_s64(numers, magic);
+ __m512i q = libdivide_mullhi_s64_vector(numers, _mm512_set1_epi64(magic));
+ q = _mm512_add_epi64(q, numers); // q += numers
+
+ // If q is non-negative, we have nothing to do.
+ // If q is negative, we want to add either (2**shift)-1 if d is
+ // a power of 2, or (2**shift) if it is not a power of 2.
+ uint32_t is_power_of_2 = (magic == 0);
+ __m512i q_sign = libdivide_s64_signbits(q); // q_sign = q >> 63
+ __m512i mask = _mm512_set1_epi64((1ULL << shift) - is_power_of_2);
+ q = _mm512_add_epi64(q, _mm512_and_si512(q_sign, mask)); // q = q + (q_sign & mask)
+ q = libdivide_s64_shift_right_vector(q, shift); // q >>= shift
+ q = _mm512_sub_epi64(_mm512_xor_si512(q, sign), sign); // q = (q ^ sign) - sign
+ return q;
+}
+
+#elif defined(LIBDIVIDE_AVX2)
+
+static inline __m256i libdivide_u32_do_vector(__m256i numers, const struct libdivide_u32_t *denom);
+static inline __m256i libdivide_s32_do_vector(__m256i numers, const struct libdivide_s32_t *denom);
+static inline __m256i libdivide_u64_do_vector(__m256i numers, const struct libdivide_u64_t *denom);
+static inline __m256i libdivide_s64_do_vector(__m256i numers, const struct libdivide_s64_t *denom);
+
+static inline __m256i libdivide_u32_branchfree_do_vector(__m256i numers, const struct libdivide_u32_branchfree_t *denom);
+static inline __m256i libdivide_s32_branchfree_do_vector(__m256i numers, const struct libdivide_s32_branchfree_t *denom);
+static inline __m256i libdivide_u64_branchfree_do_vector(__m256i numers, const struct libdivide_u64_branchfree_t *denom);
+static inline __m256i libdivide_s64_branchfree_do_vector(__m256i numers, const struct libdivide_s64_branchfree_t *denom);
+
+//////// Internal Utility Functions
+
+// Implementation of _mm256_srai_epi64(v, 63) (from AVX512).
+static inline __m256i libdivide_s64_signbits(__m256i v) {
+ __m256i hiBitsDuped = _mm256_shuffle_epi32(v, _MM_SHUFFLE(3, 3, 1, 1));
+ __m256i signBits = _mm256_srai_epi32(hiBitsDuped, 31);
+ return signBits;
+}
+
+// Implementation of _mm256_srai_epi64 (from AVX512).
+static inline __m256i libdivide_s64_shift_right_vector(__m256i v, int amt) {
+ const int b = 64 - amt;
+ __m256i m = _mm256_set1_epi64x(1ULL << (b - 1));
+ __m256i x = _mm256_srli_epi64(v, amt);
+ __m256i result = _mm256_sub_epi64(_mm256_xor_si256(x, m), m);
+ return result;
+}
+
+// Here, b is assumed to contain one 32-bit value repeated.
+static inline __m256i libdivide_mullhi_u32_vector(__m256i a, __m256i b) {
+ __m256i hi_product_0Z2Z = _mm256_srli_epi64(_mm256_mul_epu32(a, b), 32);
+ __m256i a1X3X = _mm256_srli_epi64(a, 32);
+ __m256i mask = _mm256_set_epi32(-1, 0, -1, 0, -1, 0, -1, 0);
+ __m256i hi_product_Z1Z3 = _mm256_and_si256(_mm256_mul_epu32(a1X3X, b), mask);
+ return _mm256_or_si256(hi_product_0Z2Z, hi_product_Z1Z3);
+}
+
+// b is one 32-bit value repeated.
+static inline __m256i libdivide_mullhi_s32_vector(__m256i a, __m256i b) {
+ __m256i hi_product_0Z2Z = _mm256_srli_epi64(_mm256_mul_epi32(a, b), 32);
+ __m256i a1X3X = _mm256_srli_epi64(a, 32);
+ __m256i mask = _mm256_set_epi32(-1, 0, -1, 0, -1, 0, -1, 0);
+ __m256i hi_product_Z1Z3 = _mm256_and_si256(_mm256_mul_epi32(a1X3X, b), mask);
+ return _mm256_or_si256(hi_product_0Z2Z, hi_product_Z1Z3);
+}
+
+// Here, y is assumed to contain one 64-bit value repeated.
+// https://stackoverflow.com/a/28827013
+static inline __m256i libdivide_mullhi_u64_vector(__m256i x, __m256i y) {
+ __m256i lomask = _mm256_set1_epi64x(0xffffffff);
+ __m256i xh = _mm256_shuffle_epi32(x, 0xB1); // x0l, x0h, x1l, x1h
+ __m256i yh = _mm256_shuffle_epi32(y, 0xB1); // y0l, y0h, y1l, y1h
+ __m256i w0 = _mm256_mul_epu32(x, y); // x0l*y0l, x1l*y1l
+ __m256i w1 = _mm256_mul_epu32(x, yh); // x0l*y0h, x1l*y1h
+ __m256i w2 = _mm256_mul_epu32(xh, y); // x0h*y0l, x1h*y0l
+ __m256i w3 = _mm256_mul_epu32(xh, yh); // x0h*y0h, x1h*y1h
+ __m256i w0h = _mm256_srli_epi64(w0, 32);
+ __m256i s1 = _mm256_add_epi64(w1, w0h);
+ __m256i s1l = _mm256_and_si256(s1, lomask);
+ __m256i s1h = _mm256_srli_epi64(s1, 32);
+ __m256i s2 = _mm256_add_epi64(w2, s1l);
+ __m256i s2h = _mm256_srli_epi64(s2, 32);
+ __m256i hi = _mm256_add_epi64(w3, s1h);
+ hi = _mm256_add_epi64(hi, s2h);
+
+ return hi;
+}
+
+// y is one 64-bit value repeated.
+static inline __m256i libdivide_mullhi_s64_vector(__m256i x, __m256i y) {
+ __m256i p = libdivide_mullhi_u64_vector(x, y);
+ __m256i t1 = _mm256_and_si256(libdivide_s64_signbits(x), y);
+ __m256i t2 = _mm256_and_si256(libdivide_s64_signbits(y), x);
+ p = _mm256_sub_epi64(p, t1);
+ p = _mm256_sub_epi64(p, t2);
+ return p;
+}
+
+////////// UINT32
+
+__m256i libdivide_u32_do_vector(__m256i numers, const struct libdivide_u32_t *denom) {
+ uint8_t more = denom->more;
+ if (!denom->magic) {
+ return _mm256_srli_epi32(numers, more);
+ }
+ else {
+ __m256i q = libdivide_mullhi_u32_vector(numers, _mm256_set1_epi32(denom->magic));
+ if (more & LIBDIVIDE_ADD_MARKER) {
+ // uint32_t t = ((numer - q) >> 1) + q;
+ // return t >> denom->shift;
+ uint32_t shift = more & LIBDIVIDE_32_SHIFT_MASK;
+ __m256i t = _mm256_add_epi32(_mm256_srli_epi32(_mm256_sub_epi32(numers, q), 1), q);
+ return _mm256_srli_epi32(t, shift);
+ }
+ else {
+ return _mm256_srli_epi32(q, more);
+ }
+ }
+}
+
+__m256i libdivide_u32_branchfree_do_vector(__m256i numers, const struct libdivide_u32_branchfree_t *denom) {
+ __m256i q = libdivide_mullhi_u32_vector(numers, _mm256_set1_epi32(denom->magic));
+ __m256i t = _mm256_add_epi32(_mm256_srli_epi32(_mm256_sub_epi32(numers, q), 1), q);
+ return _mm256_srli_epi32(t, denom->more);
+}
+
+////////// UINT64
+
+__m256i libdivide_u64_do_vector(__m256i numers, const struct libdivide_u64_t *denom) {
+ uint8_t more = denom->more;
+ if (!denom->magic) {
+ return _mm256_srli_epi64(numers, more);
+ }
+ else {
+ __m256i q = libdivide_mullhi_u64_vector(numers, _mm256_set1_epi64x(denom->magic));
+ if (more & LIBDIVIDE_ADD_MARKER) {
+ // uint32_t t = ((numer - q) >> 1) + q;
+ // return t >> denom->shift;
+ uint32_t shift = more & LIBDIVIDE_64_SHIFT_MASK;
+ __m256i t = _mm256_add_epi64(_mm256_srli_epi64(_mm256_sub_epi64(numers, q), 1), q);
+ return _mm256_srli_epi64(t, shift);
+ }
+ else {
+ return _mm256_srli_epi64(q, more);
+ }
+ }
+}
+
+__m256i libdivide_u64_branchfree_do_vector(__m256i numers, const struct libdivide_u64_branchfree_t *denom) {
+ __m256i q = libdivide_mullhi_u64_vector(numers, _mm256_set1_epi64x(denom->magic));
+ __m256i t = _mm256_add_epi64(_mm256_srli_epi64(_mm256_sub_epi64(numers, q), 1), q);
+ return _mm256_srli_epi64(t, denom->more);
+}
+
+////////// SINT32
+
+__m256i libdivide_s32_do_vector(__m256i numers, const struct libdivide_s32_t *denom) {
+ uint8_t more = denom->more;
+ if (!denom->magic) {
+ uint32_t shift = more & LIBDIVIDE_32_SHIFT_MASK;
+ uint32_t mask = (1U << shift) - 1;
+ __m256i roundToZeroTweak = _mm256_set1_epi32(mask);
+ // q = numer + ((numer >> 31) & roundToZeroTweak);
+ __m256i q = _mm256_add_epi32(numers, _mm256_and_si256(_mm256_srai_epi32(numers, 31), roundToZeroTweak));
+ q = _mm256_srai_epi32(q, shift);
+ __m256i sign = _mm256_set1_epi32((int8_t)more >> 7);
+ // q = (q ^ sign) - sign;
+ q = _mm256_sub_epi32(_mm256_xor_si256(q, sign), sign);
+ return q;
+ }
+ else {
+ __m256i q = libdivide_mullhi_s32_vector(numers, _mm256_set1_epi32(denom->magic));
+ if (more & LIBDIVIDE_ADD_MARKER) {
+ // must be arithmetic shift
+ __m256i sign = _mm256_set1_epi32((int8_t)more >> 7);
+ // q += ((numer ^ sign) - sign);
+ q = _mm256_add_epi32(q, _mm256_sub_epi32(_mm256_xor_si256(numers, sign), sign));
+ }
+ // q >>= shift
+ q = _mm256_srai_epi32(q, more & LIBDIVIDE_32_SHIFT_MASK);
+ q = _mm256_add_epi32(q, _mm256_srli_epi32(q, 31)); // q += (q < 0)
+ return q;
+ }
+}
+
+__m256i libdivide_s32_branchfree_do_vector(__m256i numers, const struct libdivide_s32_branchfree_t *denom) {
+ int32_t magic = denom->magic;
+ uint8_t more = denom->more;
+ uint8_t shift = more & LIBDIVIDE_32_SHIFT_MASK;
+ // must be arithmetic shift
+ __m256i sign = _mm256_set1_epi32((int8_t)more >> 7);
+ __m256i q = libdivide_mullhi_s32_vector(numers, _mm256_set1_epi32(magic));
+ q = _mm256_add_epi32(q, numers); // q += numers
+
+ // If q is non-negative, we have nothing to do
+ // If q is negative, we want to add either (2**shift)-1 if d is
+ // a power of 2, or (2**shift) if it is not a power of 2
+ uint32_t is_power_of_2 = (magic == 0);
+ __m256i q_sign = _mm256_srai_epi32(q, 31); // q_sign = q >> 31
+ __m256i mask = _mm256_set1_epi32((1U << shift) - is_power_of_2);
+ q = _mm256_add_epi32(q, _mm256_and_si256(q_sign, mask)); // q = q + (q_sign & mask)
+ q = _mm256_srai_epi32(q, shift); // q >>= shift
+ q = _mm256_sub_epi32(_mm256_xor_si256(q, sign), sign); // q = (q ^ sign) - sign
+ return q;
+}
+
+////////// SINT64
+
+__m256i libdivide_s64_do_vector(__m256i numers, const struct libdivide_s64_t *denom) {
+ uint8_t more = denom->more;
+ int64_t magic = denom->magic;
+ if (magic == 0) { // shift path
+ uint32_t shift = more & LIBDIVIDE_64_SHIFT_MASK;
+ uint64_t mask = (1ULL << shift) - 1;
+ __m256i roundToZeroTweak = _mm256_set1_epi64x(mask);
+ // q = numer + ((numer >> 63) & roundToZeroTweak);
+ __m256i q = _mm256_add_epi64(numers, _mm256_and_si256(libdivide_s64_signbits(numers), roundToZeroTweak));
+ q = libdivide_s64_shift_right_vector(q, shift);
+ __m256i sign = _mm256_set1_epi32((int8_t)more >> 7);
+ // q = (q ^ sign) - sign;
+ q = _mm256_sub_epi64(_mm256_xor_si256(q, sign), sign);
+ return q;
+ }
+ else {
+ __m256i q = libdivide_mullhi_s64_vector(numers, _mm256_set1_epi64x(magic));
+ if (more & LIBDIVIDE_ADD_MARKER) {
+ // must be arithmetic shift
+ __m256i sign = _mm256_set1_epi32((int8_t)more >> 7);
+ // q += ((numer ^ sign) - sign);
+ q = _mm256_add_epi64(q, _mm256_sub_epi64(_mm256_xor_si256(numers, sign), sign));
+ }
+ // q >>= denom->mult_path.shift
+ q = libdivide_s64_shift_right_vector(q, more & LIBDIVIDE_64_SHIFT_MASK);
+ q = _mm256_add_epi64(q, _mm256_srli_epi64(q, 63)); // q += (q < 0)
+ return q;
+ }
+}
+
+__m256i libdivide_s64_branchfree_do_vector(__m256i numers, const struct libdivide_s64_branchfree_t *denom) {
+ int64_t magic = denom->magic;
+ uint8_t more = denom->more;
+ uint8_t shift = more & LIBDIVIDE_64_SHIFT_MASK;
+ // must be arithmetic shift
+ __m256i sign = _mm256_set1_epi32((int8_t)more >> 7);
+
+ // libdivide_mullhi_s64(numers, magic);
+ __m256i q = libdivide_mullhi_s64_vector(numers, _mm256_set1_epi64x(magic));
+ q = _mm256_add_epi64(q, numers); // q += numers
+
+ // If q is non-negative, we have nothing to do.
+ // If q is negative, we want to add either (2**shift)-1 if d is
+ // a power of 2, or (2**shift) if it is not a power of 2.
+ uint32_t is_power_of_2 = (magic == 0);
+ __m256i q_sign = libdivide_s64_signbits(q); // q_sign = q >> 63
+ __m256i mask = _mm256_set1_epi64x((1ULL << shift) - is_power_of_2);
+ q = _mm256_add_epi64(q, _mm256_and_si256(q_sign, mask)); // q = q + (q_sign & mask)
+ q = libdivide_s64_shift_right_vector(q, shift); // q >>= shift
+ q = _mm256_sub_epi64(_mm256_xor_si256(q, sign), sign); // q = (q ^ sign) - sign
+ return q;
+}
+
+#elif defined(LIBDIVIDE_SSE2)
+
+static inline __m128i libdivide_u32_do_vector(__m128i numers, const struct libdivide_u32_t *denom);
+static inline __m128i libdivide_s32_do_vector(__m128i numers, const struct libdivide_s32_t *denom);
+static inline __m128i libdivide_u64_do_vector(__m128i numers, const struct libdivide_u64_t *denom);
+static inline __m128i libdivide_s64_do_vector(__m128i numers, const struct libdivide_s64_t *denom);
+
+static inline __m128i libdivide_u32_branchfree_do_vector(__m128i numers, const struct libdivide_u32_branchfree_t *denom);
+static inline __m128i libdivide_s32_branchfree_do_vector(__m128i numers, const struct libdivide_s32_branchfree_t *denom);
+static inline __m128i libdivide_u64_branchfree_do_vector(__m128i numers, const struct libdivide_u64_branchfree_t *denom);
+static inline __m128i libdivide_s64_branchfree_do_vector(__m128i numers, const struct libdivide_s64_branchfree_t *denom);
+
+//////// Internal Utility Functions
+
+// Implementation of _mm_srai_epi64(v, 63) (from AVX512).
+static inline __m128i libdivide_s64_signbits(__m128i v) {
+ __m128i hiBitsDuped = _mm_shuffle_epi32(v, _MM_SHUFFLE(3, 3, 1, 1));
+ __m128i signBits = _mm_srai_epi32(hiBitsDuped, 31);
+ return signBits;
+}
+
+// Implementation of _mm_srai_epi64 (from AVX512).
+static inline __m128i libdivide_s64_shift_right_vector(__m128i v, int amt) {
+ const int b = 64 - amt;
+ __m128i m = _mm_set1_epi64x(1ULL << (b - 1));
+ __m128i x = _mm_srli_epi64(v, amt);
+ __m128i result = _mm_sub_epi64(_mm_xor_si128(x, m), m);
+ return result;
+}
+
+// Here, b is assumed to contain one 32-bit value repeated.
+static inline __m128i libdivide_mullhi_u32_vector(__m128i a, __m128i b) {
+ __m128i hi_product_0Z2Z = _mm_srli_epi64(_mm_mul_epu32(a, b), 32);
+ __m128i a1X3X = _mm_srli_epi64(a, 32);
+ __m128i mask = _mm_set_epi32(-1, 0, -1, 0);
+ __m128i hi_product_Z1Z3 = _mm_and_si128(_mm_mul_epu32(a1X3X, b), mask);
+ return _mm_or_si128(hi_product_0Z2Z, hi_product_Z1Z3);
+}
+
+// SSE2 does not have a signed multiplication instruction, but we can convert
+// unsigned to signed pretty efficiently. Again, b is just a 32 bit value
+// repeated four times.
+static inline __m128i libdivide_mullhi_s32_vector(__m128i a, __m128i b) {
+ __m128i p = libdivide_mullhi_u32_vector(a, b);
+ // t1 = (a >> 31) & y, arithmetic shift
+ __m128i t1 = _mm_and_si128(_mm_srai_epi32(a, 31), b);
+ __m128i t2 = _mm_and_si128(_mm_srai_epi32(b, 31), a);
+ p = _mm_sub_epi32(p, t1);
+ p = _mm_sub_epi32(p, t2);
+ return p;
+}
+
+// Here, y is assumed to contain one 64-bit value repeated.
+// https://stackoverflow.com/a/28827013
+static inline __m128i libdivide_mullhi_u64_vector(__m128i x, __m128i y) {
+ __m128i lomask = _mm_set1_epi64x(0xffffffff);
+ __m128i xh = _mm_shuffle_epi32(x, 0xB1); // x0l, x0h, x1l, x1h
+ __m128i yh = _mm_shuffle_epi32(y, 0xB1); // y0l, y0h, y1l, y1h
+ __m128i w0 = _mm_mul_epu32(x, y); // x0l*y0l, x1l*y1l
+ __m128i w1 = _mm_mul_epu32(x, yh); // x0l*y0h, x1l*y1h
+ __m128i w2 = _mm_mul_epu32(xh, y); // x0h*y0l, x1h*y0l
+ __m128i w3 = _mm_mul_epu32(xh, yh); // x0h*y0h, x1h*y1h
+ __m128i w0h = _mm_srli_epi64(w0, 32);
+ __m128i s1 = _mm_add_epi64(w1, w0h);
+ __m128i s1l = _mm_and_si128(s1, lomask);
+ __m128i s1h = _mm_srli_epi64(s1, 32);
+ __m128i s2 = _mm_add_epi64(w2, s1l);
+ __m128i s2h = _mm_srli_epi64(s2, 32);
+ __m128i hi = _mm_add_epi64(w3, s1h);
+ hi = _mm_add_epi64(hi, s2h);
+
+ return hi;
+}
+
+// y is one 64-bit value repeated.
+static inline __m128i libdivide_mullhi_s64_vector(__m128i x, __m128i y) {
+ __m128i p = libdivide_mullhi_u64_vector(x, y);
+ __m128i t1 = _mm_and_si128(libdivide_s64_signbits(x), y);
+ __m128i t2 = _mm_and_si128(libdivide_s64_signbits(y), x);
+ p = _mm_sub_epi64(p, t1);
+ p = _mm_sub_epi64(p, t2);
+ return p;
+}
+
+////////// UINT32
+
+__m128i libdivide_u32_do_vector(__m128i numers, const struct libdivide_u32_t *denom) {
+ uint8_t more = denom->more;
+ if (!denom->magic) {
+ return _mm_srli_epi32(numers, more);
+ }
+ else {
+ __m128i q = libdivide_mullhi_u32_vector(numers, _mm_set1_epi32(denom->magic));
+ if (more & LIBDIVIDE_ADD_MARKER) {
+ // uint32_t t = ((numer - q) >> 1) + q;
+ // return t >> denom->shift;
+ uint32_t shift = more & LIBDIVIDE_32_SHIFT_MASK;
+ __m128i t = _mm_add_epi32(_mm_srli_epi32(_mm_sub_epi32(numers, q), 1), q);
+ return _mm_srli_epi32(t, shift);
+ }
+ else {
+ return _mm_srli_epi32(q, more);
+ }
+ }
+}
+
+__m128i libdivide_u32_branchfree_do_vector(__m128i numers, const struct libdivide_u32_branchfree_t *denom) {
+ __m128i q = libdivide_mullhi_u32_vector(numers, _mm_set1_epi32(denom->magic));
+ __m128i t = _mm_add_epi32(_mm_srli_epi32(_mm_sub_epi32(numers, q), 1), q);
+ return _mm_srli_epi32(t, denom->more);
+}
+
+////////// UINT64
+
+__m128i libdivide_u64_do_vector(__m128i numers, const struct libdivide_u64_t *denom) {
+ uint8_t more = denom->more;
+ if (!denom->magic) {
+ return _mm_srli_epi64(numers, more);
+ }
+ else {
+ __m128i q = libdivide_mullhi_u64_vector(numers, _mm_set1_epi64x(denom->magic));
+ if (more & LIBDIVIDE_ADD_MARKER) {
+ // uint32_t t = ((numer - q) >> 1) + q;
+ // return t >> denom->shift;
+ uint32_t shift = more & LIBDIVIDE_64_SHIFT_MASK;
+ __m128i t = _mm_add_epi64(_mm_srli_epi64(_mm_sub_epi64(numers, q), 1), q);
+ return _mm_srli_epi64(t, shift);
+ }
+ else {
+ return _mm_srli_epi64(q, more);
+ }
+ }
+}
+
+__m128i libdivide_u64_branchfree_do_vector(__m128i numers, const struct libdivide_u64_branchfree_t *denom) {
+ __m128i q = libdivide_mullhi_u64_vector(numers, _mm_set1_epi64x(denom->magic));
+ __m128i t = _mm_add_epi64(_mm_srli_epi64(_mm_sub_epi64(numers, q), 1), q);
+ return _mm_srli_epi64(t, denom->more);
+}
+
+////////// SINT32
+
+__m128i libdivide_s32_do_vector(__m128i numers, const struct libdivide_s32_t *denom) {
+ uint8_t more = denom->more;
+ if (!denom->magic) {
+ uint32_t shift = more & LIBDIVIDE_32_SHIFT_MASK;
+ uint32_t mask = (1U << shift) - 1;
+ __m128i roundToZeroTweak = _mm_set1_epi32(mask);
+ // q = numer + ((numer >> 31) & roundToZeroTweak);
+ __m128i q = _mm_add_epi32(numers, _mm_and_si128(_mm_srai_epi32(numers, 31), roundToZeroTweak));
+ q = _mm_srai_epi32(q, shift);
+ __m128i sign = _mm_set1_epi32((int8_t)more >> 7);
+ // q = (q ^ sign) - sign;
+ q = _mm_sub_epi32(_mm_xor_si128(q, sign), sign);
+ return q;
+ }
+ else {
+ __m128i q = libdivide_mullhi_s32_vector(numers, _mm_set1_epi32(denom->magic));
+ if (more & LIBDIVIDE_ADD_MARKER) {
+ // must be arithmetic shift
+ __m128i sign = _mm_set1_epi32((int8_t)more >> 7);
+ // q += ((numer ^ sign) - sign);
+ q = _mm_add_epi32(q, _mm_sub_epi32(_mm_xor_si128(numers, sign), sign));
+ }
+ // q >>= shift
+ q = _mm_srai_epi32(q, more & LIBDIVIDE_32_SHIFT_MASK);
+ q = _mm_add_epi32(q, _mm_srli_epi32(q, 31)); // q += (q < 0)
+ return q;
+ }
+}
+
+__m128i libdivide_s32_branchfree_do_vector(__m128i numers, const struct libdivide_s32_branchfree_t *denom) {
+ int32_t magic = denom->magic;
+ uint8_t more = denom->more;
+ uint8_t shift = more & LIBDIVIDE_32_SHIFT_MASK;
+ // must be arithmetic shift
+ __m128i sign = _mm_set1_epi32((int8_t)more >> 7);
+ __m128i q = libdivide_mullhi_s32_vector(numers, _mm_set1_epi32(magic));
+ q = _mm_add_epi32(q, numers); // q += numers
+
+ // If q is non-negative, we have nothing to do
+ // If q is negative, we want to add either (2**shift)-1 if d is
+ // a power of 2, or (2**shift) if it is not a power of 2
+ uint32_t is_power_of_2 = (magic == 0);
+ __m128i q_sign = _mm_srai_epi32(q, 31); // q_sign = q >> 31
+ __m128i mask = _mm_set1_epi32((1U << shift) - is_power_of_2);
+ q = _mm_add_epi32(q, _mm_and_si128(q_sign, mask)); // q = q + (q_sign & mask)
+ q = _mm_srai_epi32(q, shift); // q >>= shift
+ q = _mm_sub_epi32(_mm_xor_si128(q, sign), sign); // q = (q ^ sign) - sign
+ return q;
+}
+
+////////// SINT64
+
+__m128i libdivide_s64_do_vector(__m128i numers, const struct libdivide_s64_t *denom) {
+ uint8_t more = denom->more;
+ int64_t magic = denom->magic;
+ if (magic == 0) { // shift path
+ uint32_t shift = more & LIBDIVIDE_64_SHIFT_MASK;
+ uint64_t mask = (1ULL << shift) - 1;
+ __m128i roundToZeroTweak = _mm_set1_epi64x(mask);
+ // q = numer + ((numer >> 63) & roundToZeroTweak);
+ __m128i q = _mm_add_epi64(numers, _mm_and_si128(libdivide_s64_signbits(numers), roundToZeroTweak));
+ q = libdivide_s64_shift_right_vector(q, shift);
+ __m128i sign = _mm_set1_epi32((int8_t)more >> 7);
+ // q = (q ^ sign) - sign;
+ q = _mm_sub_epi64(_mm_xor_si128(q, sign), sign);
+ return q;
+ }
+ else {
+ __m128i q = libdivide_mullhi_s64_vector(numers, _mm_set1_epi64x(magic));
+ if (more & LIBDIVIDE_ADD_MARKER) {
+ // must be arithmetic shift
+ __m128i sign = _mm_set1_epi32((int8_t)more >> 7);
+ // q += ((numer ^ sign) - sign);
+ q = _mm_add_epi64(q, _mm_sub_epi64(_mm_xor_si128(numers, sign), sign));
+ }
+ // q >>= denom->mult_path.shift
+ q = libdivide_s64_shift_right_vector(q, more & LIBDIVIDE_64_SHIFT_MASK);
+ q = _mm_add_epi64(q, _mm_srli_epi64(q, 63)); // q += (q < 0)
+ return q;
+ }
+}
+
+__m128i libdivide_s64_branchfree_do_vector(__m128i numers, const struct libdivide_s64_branchfree_t *denom) {
+ int64_t magic = denom->magic;
+ uint8_t more = denom->more;
+ uint8_t shift = more & LIBDIVIDE_64_SHIFT_MASK;
+ // must be arithmetic shift
+ __m128i sign = _mm_set1_epi32((int8_t)more >> 7);
+
+ // libdivide_mullhi_s64(numers, magic);
+ __m128i q = libdivide_mullhi_s64_vector(numers, _mm_set1_epi64x(magic));
+ q = _mm_add_epi64(q, numers); // q += numers
+
+ // If q is non-negative, we have nothing to do.
+ // If q is negative, we want to add either (2**shift)-1 if d is
+ // a power of 2, or (2**shift) if it is not a power of 2.
+ uint32_t is_power_of_2 = (magic == 0);
+ __m128i q_sign = libdivide_s64_signbits(q); // q_sign = q >> 63
+ __m128i mask = _mm_set1_epi64x((1ULL << shift) - is_power_of_2);
+ q = _mm_add_epi64(q, _mm_and_si128(q_sign, mask)); // q = q + (q_sign & mask)
+ q = libdivide_s64_shift_right_vector(q, shift); // q >>= shift
+ q = _mm_sub_epi64(_mm_xor_si128(q, sign), sign); // q = (q ^ sign) - sign
+ return q;
+}
+
+#endif
+
+/////////// C++ stuff
+
+#ifdef __cplusplus
+
+// The C++ divider class is templated on both an integer type
+// (like uint64_t) and an algorithm type.
+// * BRANCHFULL is the default algorithm type.
+// * BRANCHFREE is the branchfree algorithm type.
+enum {
+ BRANCHFULL,
+ BRANCHFREE
+};
+
+#if defined(LIBDIVIDE_AVX512)
+ #define LIBDIVIDE_VECTOR_TYPE __m512i
+#elif defined(LIBDIVIDE_AVX2)
+ #define LIBDIVIDE_VECTOR_TYPE __m256i
+#elif defined(LIBDIVIDE_SSE2)
+ #define LIBDIVIDE_VECTOR_TYPE __m128i
+#endif
+
+#if !defined(LIBDIVIDE_VECTOR_TYPE)
+ #define LIBDIVIDE_DIVIDE_VECTOR(ALGO)
+#else
+ #define LIBDIVIDE_DIVIDE_VECTOR(ALGO) \
+ LIBDIVIDE_VECTOR_TYPE divide(LIBDIVIDE_VECTOR_TYPE n) const { \
+ return libdivide_##ALGO##_do_vector(n, &denom); \
+ }
+#endif
+
+// The DISPATCHER_GEN() macro generates C++ methods (for the given integer
+// and algorithm types) that redirect to libdivide's C API.
+#define DISPATCHER_GEN(T, ALGO) \
+ libdivide_##ALGO##_t denom; \
+ dispatcher() { } \
+ dispatcher(T d) \
+ : denom(libdivide_##ALGO##_gen(d)) \
+ { } \
+ T divide(T n) const { \
+ return libdivide_##ALGO##_do(n, &denom); \
+ } \
+ LIBDIVIDE_DIVIDE_VECTOR(ALGO) \
+ T recover() const { \
+ return libdivide_##ALGO##_recover(&denom); \
+ }
+
+// The dispatcher selects a specific division algorithm for a given
+// type and ALGO using partial template specialization.
+template struct dispatcher { };
+
+template<> struct dispatcher { DISPATCHER_GEN(int32_t, s32) };
+template<> struct dispatcher { DISPATCHER_GEN(int32_t, s32_branchfree) };
+template<> struct dispatcher { DISPATCHER_GEN(uint32_t, u32) };
+template<> struct dispatcher { DISPATCHER_GEN(uint32_t, u32_branchfree) };
+template<> struct dispatcher { DISPATCHER_GEN(int64_t, s64) };
+template<> struct dispatcher { DISPATCHER_GEN(int64_t, s64_branchfree) };
+template<> struct dispatcher { DISPATCHER_GEN(uint64_t, u64) };
+template<> struct dispatcher { DISPATCHER_GEN(uint64_t, u64_branchfree) };
+
+// This is the main divider class for use by the user (C++ API).
+// The actual division algorithm is selected using the dispatcher struct
+// based on the integer and algorithm template parameters.
+template
+class divider {
+public:
+ // We leave the default constructor empty so that creating
+ // an array of dividers and then initializing them
+ // later doesn't slow us down.
+ divider() { }
+
+ // Constructor that takes the divisor as a parameter
+ divider(T d) : div(d) { }
+
+ // Divides n by the divisor
+ T divide(T n) const {
+ return div.divide(n);
+ }
+
+ // Recovers the divisor, returns the value that was
+ // used to initialize this divider object.
+ T recover() const {
+ return div.recover();
+ }
+
+ bool operator==(const divider& other) const {
+ return div.denom.magic == other.denom.magic &&
+ div.denom.more == other.denom.more;
+ }
+
+ bool operator!=(const divider& other) const {
+ return !(*this == other);
+ }
+
+#if defined(LIBDIVIDE_VECTOR_TYPE)
+ // Treats the vector as packed integer values with the same type as
+ // the divider (e.g. s32, u32, s64, u64) and divides each of
+ // them by the divider, returning the packed quotients.
+ LIBDIVIDE_VECTOR_TYPE divide(LIBDIVIDE_VECTOR_TYPE n) const {
+ return div.divide(n);
+ }
+#endif
+
+private:
+ // Storage for the actual divisor
+ dispatcher::value,
+ std::is_signed::value, sizeof(T), ALGO> div;
+};
+
+// Overload of operator / for scalar division
+template
+T operator/(T n, const divider& div) {
+ return div.divide(n);
+}
+
+// Overload of operator /= for scalar division
+template
+T& operator/=(T& n, const divider& div) {
+ n = div.divide(n);
+ return n;
+}
+
+#if defined(LIBDIVIDE_VECTOR_TYPE)
+ // Overload of operator / for vector division
+ template
+ LIBDIVIDE_VECTOR_TYPE operator/(LIBDIVIDE_VECTOR_TYPE n, const divider& div) {
+ return div.divide(n);
+ }
+ // Overload of operator /= for vector division
+ template
+ LIBDIVIDE_VECTOR_TYPE& operator/=(LIBDIVIDE_VECTOR_TYPE& n, const divider& div) {
+ n = div.divide(n);
+ return n;
+ }
+#endif
+
+// libdivdie::branchfree_divider
+template
+using branchfree_divider = divider;
+
+} // namespace libdivide
+
+#endif // __cplusplus
+
+#endif // NUMPY_CORE_INCLUDE_NUMPY_LIBDIVIDE_LIBDIVIDE_H_
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/ufuncobject.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/ufuncobject.h
new file mode 100644
index 0000000000000000000000000000000000000000..169a93eb5597777b67733cb5806bca7a2d38cc56
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/ufuncobject.h
@@ -0,0 +1,347 @@
+#ifndef NUMPY_CORE_INCLUDE_NUMPY_UFUNCOBJECT_H_
+#define NUMPY_CORE_INCLUDE_NUMPY_UFUNCOBJECT_H_
+
+#include
+#include
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * The legacy generic inner loop for a standard element-wise or
+ * generalized ufunc.
+ */
+typedef void (*PyUFuncGenericFunction)
+ (char **args,
+ npy_intp const *dimensions,
+ npy_intp const *strides,
+ void *innerloopdata);
+
+/*
+ * The most generic one-dimensional inner loop for
+ * a masked standard element-wise ufunc. "Masked" here means that it skips
+ * doing calculations on any items for which the maskptr array has a true
+ * value.
+ */
+typedef void (PyUFunc_MaskedStridedInnerLoopFunc)(
+ char **dataptrs, npy_intp *strides,
+ char *maskptr, npy_intp mask_stride,
+ npy_intp count,
+ NpyAuxData *innerloopdata);
+
+/* Forward declaration for the type resolver and loop selector typedefs */
+struct _tagPyUFuncObject;
+
+/*
+ * Given the operands for calling a ufunc, should determine the
+ * calculation input and output data types and return an inner loop function.
+ * This function should validate that the casting rule is being followed,
+ * and fail if it is not.
+ *
+ * For backwards compatibility, the regular type resolution function does not
+ * support auxiliary data with object semantics. The type resolution call
+ * which returns a masked generic function returns a standard NpyAuxData
+ * object, for which the NPY_AUXDATA_FREE and NPY_AUXDATA_CLONE macros
+ * work.
+ *
+ * ufunc: The ufunc object.
+ * casting: The 'casting' parameter provided to the ufunc.
+ * operands: An array of length (ufunc->nin + ufunc->nout),
+ * with the output parameters possibly NULL.
+ * type_tup: Either NULL, or the type_tup passed to the ufunc.
+ * out_dtypes: An array which should be populated with new
+ * references to (ufunc->nin + ufunc->nout) new
+ * dtypes, one for each input and output. These
+ * dtypes should all be in native-endian format.
+ *
+ * Should return 0 on success, -1 on failure (with exception set),
+ * or -2 if Py_NotImplemented should be returned.
+ */
+typedef int (PyUFunc_TypeResolutionFunc)(
+ struct _tagPyUFuncObject *ufunc,
+ NPY_CASTING casting,
+ PyArrayObject **operands,
+ PyObject *type_tup,
+ PyArray_Descr **out_dtypes);
+
+/*
+ * This is the signature for the functions that may be assigned to the
+ * `process_core_dims_func` field of the PyUFuncObject structure.
+ * Implementation of this function is optional. This function is only used
+ * by generalized ufuncs (i.e. those with the field `core_enabled` set to 1).
+ * The function is called by the ufunc during the processing of the arguments
+ * of a call of the ufunc. The function can check the core dimensions of the
+ * input and output arrays and return -1 with an exception set if any
+ * requirements are not satisfied. If the caller of the ufunc didn't provide
+ * output arrays, the core dimensions associated with the output arrays (i.e.
+ * those that are not also used in input arrays) will have the value -1 in
+ * `core_dim_sizes`. This function can replace any output core dimensions
+ * that are -1 with a value that is appropriate for the ufunc.
+ *
+ * Parameter Description
+ * --------------- ------------------------------------------------------
+ * ufunc The ufunc object
+ * core_dim_sizes An array with length `ufunc->core_num_dim_ix`.
+ * The core dimensions of the arrays passed to the ufunc
+ * will have been set. If the caller of the ufunc didn't
+ * provide the output array(s), the output-only core
+ * dimensions will have the value -1.
+ *
+ * The function must not change any element in `core_dim_sizes` that is
+ * not -1 on input. Doing so will result in incorrect output from the
+ * ufunc, and could result in a crash of the Python interpreter.
+ *
+ * The function must return 0 on success, -1 on failure (with an exception
+ * set).
+ */
+typedef int (PyUFunc_ProcessCoreDimsFunc)(
+ struct _tagPyUFuncObject *ufunc,
+ npy_intp *core_dim_sizes);
+
+typedef struct _tagPyUFuncObject {
+ PyObject_HEAD
+ /*
+ * nin: Number of inputs
+ * nout: Number of outputs
+ * nargs: Always nin + nout (Why is it stored?)
+ */
+ int nin, nout, nargs;
+
+ /*
+ * Identity for reduction, any of PyUFunc_One, PyUFunc_Zero
+ * PyUFunc_MinusOne, PyUFunc_None, PyUFunc_ReorderableNone,
+ * PyUFunc_IdentityValue.
+ */
+ int identity;
+
+ /* Array of one-dimensional core loops */
+ PyUFuncGenericFunction *functions;
+ /* Array of funcdata that gets passed into the functions */
+ void *const *data;
+ /* The number of elements in 'functions' and 'data' */
+ int ntypes;
+
+ /* Used to be unused field 'check_return' */
+ int reserved1;
+
+ /* The name of the ufunc */
+ const char *name;
+
+ /* Array of type numbers, of size ('nargs' * 'ntypes') */
+ const char *types;
+
+ /* Documentation string */
+ const char *doc;
+
+ void *ptr;
+ PyObject *obj;
+ PyObject *userloops;
+
+ /* generalized ufunc parameters */
+
+ /* 0 for scalar ufunc; 1 for generalized ufunc */
+ int core_enabled;
+ /* number of distinct dimension names in signature */
+ int core_num_dim_ix;
+
+ /*
+ * dimension indices of input/output argument k are stored in
+ * core_dim_ixs[core_offsets[k]..core_offsets[k]+core_num_dims[k]-1]
+ */
+
+ /* numbers of core dimensions of each argument */
+ int *core_num_dims;
+ /*
+ * dimension indices in a flatted form; indices
+ * are in the range of [0,core_num_dim_ix)
+ */
+ int *core_dim_ixs;
+ /*
+ * positions of 1st core dimensions of each
+ * argument in core_dim_ixs, equivalent to cumsum(core_num_dims)
+ */
+ int *core_offsets;
+ /* signature string for printing purpose */
+ char *core_signature;
+
+ /*
+ * A function which resolves the types and fills an array
+ * with the dtypes for the inputs and outputs.
+ */
+ PyUFunc_TypeResolutionFunc *type_resolver;
+
+ /* A dictionary to monkeypatch ufuncs */
+ PyObject *dict;
+
+ /*
+ * This was blocked off to be the "new" inner loop selector in 1.7,
+ * but this was never implemented. (This is also why the above
+ * selector is called the "legacy" selector.)
+ */
+ #ifndef Py_LIMITED_API
+ vectorcallfunc vectorcall;
+ #else
+ void *vectorcall;
+ #endif
+
+ /* Was previously the `PyUFunc_MaskedInnerLoopSelectionFunc` */
+ void *reserved3;
+
+ /*
+ * List of flags for each operand when ufunc is called by nditer object.
+ * These flags will be used in addition to the default flags for each
+ * operand set by nditer object.
+ */
+ npy_uint32 *op_flags;
+
+ /*
+ * List of global flags used when ufunc is called by nditer object.
+ * These flags will be used in addition to the default global flags
+ * set by nditer object.
+ */
+ npy_uint32 iter_flags;
+
+ /* New in NPY_API_VERSION 0x0000000D and above */
+ #if NPY_FEATURE_VERSION >= NPY_1_16_API_VERSION
+ /*
+ * for each core_num_dim_ix distinct dimension names,
+ * the possible "frozen" size (-1 if not frozen).
+ */
+ npy_intp *core_dim_sizes;
+
+ /*
+ * for each distinct core dimension, a set of UFUNC_CORE_DIM* flags
+ */
+ npy_uint32 *core_dim_flags;
+
+ /* Identity for reduction, when identity == PyUFunc_IdentityValue */
+ PyObject *identity_value;
+ #endif /* NPY_FEATURE_VERSION >= NPY_1_16_API_VERSION */
+
+ /* New in NPY_API_VERSION 0x0000000F and above */
+ #if NPY_FEATURE_VERSION >= NPY_1_22_API_VERSION
+ /* New private fields related to dispatching */
+ void *_dispatch_cache;
+ /* A PyListObject of `(tuple of DTypes, ArrayMethod/Promoter)` */
+ PyObject *_loops;
+ #endif
+ #if NPY_FEATURE_VERSION >= NPY_2_1_API_VERSION
+ /*
+ * Optional function to process core dimensions of a gufunc.
+ */
+ PyUFunc_ProcessCoreDimsFunc *process_core_dims_func;
+ #endif
+} PyUFuncObject;
+
+#include "arrayobject.h"
+/* Generalized ufunc; 0x0001 reserved for possible use as CORE_ENABLED */
+/* the core dimension's size will be determined by the operands. */
+#define UFUNC_CORE_DIM_SIZE_INFERRED 0x0002
+/* the core dimension may be absent */
+#define UFUNC_CORE_DIM_CAN_IGNORE 0x0004
+/* flags inferred during execution */
+#define UFUNC_CORE_DIM_MISSING 0x00040000
+
+
+#define UFUNC_OBJ_ISOBJECT 1
+#define UFUNC_OBJ_NEEDS_API 2
+
+
+#if NPY_ALLOW_THREADS
+#define NPY_LOOP_BEGIN_THREADS do {if (!(loop->obj & UFUNC_OBJ_NEEDS_API)) _save = PyEval_SaveThread();} while (0);
+#define NPY_LOOP_END_THREADS do {if (!(loop->obj & UFUNC_OBJ_NEEDS_API)) PyEval_RestoreThread(_save);} while (0);
+#else
+#define NPY_LOOP_BEGIN_THREADS
+#define NPY_LOOP_END_THREADS
+#endif
+
+/*
+ * UFunc has unit of 0, and the order of operations can be reordered
+ * This case allows reduction with multiple axes at once.
+ */
+#define PyUFunc_Zero 0
+/*
+ * UFunc has unit of 1, and the order of operations can be reordered
+ * This case allows reduction with multiple axes at once.
+ */
+#define PyUFunc_One 1
+/*
+ * UFunc has unit of -1, and the order of operations can be reordered
+ * This case allows reduction with multiple axes at once. Intended for
+ * bitwise_and reduction.
+ */
+#define PyUFunc_MinusOne 2
+/*
+ * UFunc has no unit, and the order of operations cannot be reordered.
+ * This case does not allow reduction with multiple axes at once.
+ */
+#define PyUFunc_None -1
+/*
+ * UFunc has no unit, and the order of operations can be reordered
+ * This case allows reduction with multiple axes at once.
+ */
+#define PyUFunc_ReorderableNone -2
+/*
+ * UFunc unit is an identity_value, and the order of operations can be reordered
+ * This case allows reduction with multiple axes at once.
+ */
+#define PyUFunc_IdentityValue -3
+
+
+#define UFUNC_REDUCE 0
+#define UFUNC_ACCUMULATE 1
+#define UFUNC_REDUCEAT 2
+#define UFUNC_OUTER 3
+
+
+typedef struct {
+ int nin;
+ int nout;
+ PyObject *callable;
+} PyUFunc_PyFuncData;
+
+/* A linked-list of function information for
+ user-defined 1-d loops.
+ */
+typedef struct _loop1d_info {
+ PyUFuncGenericFunction func;
+ void *data;
+ int *arg_types;
+ struct _loop1d_info *next;
+ int nargs;
+ PyArray_Descr **arg_dtypes;
+} PyUFunc_Loop1d;
+
+
+#define UFUNC_PYVALS_NAME "UFUNC_PYVALS"
+
+/*
+ * THESE MACROS ARE DEPRECATED.
+ * Use npy_set_floatstatus_* in the npymath library.
+ */
+#define UFUNC_FPE_DIVIDEBYZERO NPY_FPE_DIVIDEBYZERO
+#define UFUNC_FPE_OVERFLOW NPY_FPE_OVERFLOW
+#define UFUNC_FPE_UNDERFLOW NPY_FPE_UNDERFLOW
+#define UFUNC_FPE_INVALID NPY_FPE_INVALID
+
+#define generate_divbyzero_error() npy_set_floatstatus_divbyzero()
+#define generate_overflow_error() npy_set_floatstatus_overflow()
+
+ /* Make sure it gets defined if it isn't already */
+#ifndef UFUNC_NOFPE
+/* Clear the floating point exception default of Borland C++ */
+#if defined(__BORLANDC__)
+#define UFUNC_NOFPE _control87(MCW_EM, MCW_EM);
+#else
+#define UFUNC_NOFPE
+#endif
+#endif
+
+#include "__ufunc_api.h"
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* NUMPY_CORE_INCLUDE_NUMPY_UFUNCOBJECT_H_ */
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/utils.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/utils.h
new file mode 100644
index 0000000000000000000000000000000000000000..97f06092e54050baf3c2fc4372429cbd110429e8
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/include/numpy/utils.h
@@ -0,0 +1,37 @@
+#ifndef NUMPY_CORE_INCLUDE_NUMPY_UTILS_H_
+#define NUMPY_CORE_INCLUDE_NUMPY_UTILS_H_
+
+#ifndef __COMP_NPY_UNUSED
+ #if defined(__GNUC__)
+ #define __COMP_NPY_UNUSED __attribute__ ((__unused__))
+ #elif defined(__ICC)
+ #define __COMP_NPY_UNUSED __attribute__ ((__unused__))
+ #elif defined(__clang__)
+ #define __COMP_NPY_UNUSED __attribute__ ((unused))
+ #else
+ #define __COMP_NPY_UNUSED
+ #endif
+#endif
+
+#if defined(__GNUC__) || defined(__ICC) || defined(__clang__)
+ #define NPY_DECL_ALIGNED(x) __attribute__ ((aligned (x)))
+#elif defined(_MSC_VER)
+ #define NPY_DECL_ALIGNED(x) __declspec(align(x))
+#else
+ #define NPY_DECL_ALIGNED(x)
+#endif
+
+/* Use this to tag a variable as not used. It will remove unused variable
+ * warning on support platforms (see __COM_NPY_UNUSED) and mangle the variable
+ * to avoid accidental use */
+#define NPY_UNUSED(x) __NPY_UNUSED_TAGGED ## x __COMP_NPY_UNUSED
+#define NPY_EXPAND(x) x
+
+#define NPY_STRINGIFY(x) #x
+#define NPY_TOSTRING(x) NPY_STRINGIFY(x)
+
+#define NPY_CAT__(a, b) a ## b
+#define NPY_CAT_(a, b) NPY_CAT__(a, b)
+#define NPY_CAT(a, b) NPY_CAT_(a, b)
+
+#endif /* NUMPY_CORE_INCLUDE_NUMPY_UTILS_H_ */
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/lib/npy-pkg-config/mlib.ini b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/lib/npy-pkg-config/mlib.ini
new file mode 100644
index 0000000000000000000000000000000000000000..5840f5e1bc167f50ebc9fc98d60b60ee21ecbeec
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/lib/npy-pkg-config/mlib.ini
@@ -0,0 +1,12 @@
+[meta]
+Name = mlib
+Description = Math library used with this version of numpy
+Version = 1.0
+
+[default]
+Libs=-lm
+Cflags=
+
+[msvc]
+Libs=m.lib
+Cflags=
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/lib/npy-pkg-config/npymath.ini b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/lib/npy-pkg-config/npymath.ini
new file mode 100644
index 0000000000000000000000000000000000000000..8d879e3fb772ef04afe28bf6670a5d233acfe710
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/lib/npy-pkg-config/npymath.ini
@@ -0,0 +1,20 @@
+[meta]
+Name=npymath
+Description=Portable, core math library implementing C99 standard
+Version=0.1
+
+[variables]
+pkgname=numpy._core
+prefix=${pkgdir}
+libdir=${prefix}/lib
+includedir=${prefix}/include
+
+[default]
+Libs=-L${libdir} -lnpymath
+Cflags=-I${includedir}
+Requires=mlib
+
+[msvc]
+Libs=/LIBPATH:${libdir} npymath.lib
+Cflags=/INCLUDE:${includedir}
+Requires=mlib
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/lib/pkgconfig/numpy.pc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/lib/pkgconfig/numpy.pc
new file mode 100644
index 0000000000000000000000000000000000000000..d41fe0ae095ce21f36fd2491e21ccc3eabf1e18f
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/lib/pkgconfig/numpy.pc
@@ -0,0 +1,7 @@
+prefix=${pcfiledir}/../..
+includedir=${prefix}/include
+
+Name: numpy
+Description: NumPy is the fundamental package for scientific computing with Python.
+Version: 2.2.6
+Cflags: -I${includedir}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/memmap.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/memmap.py
new file mode 100644
index 0000000000000000000000000000000000000000..a5fa10c0e036fd6908810b0c20b401c22f75849b
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/memmap.py
@@ -0,0 +1,361 @@
+from contextlib import nullcontext
+import operator
+import numpy as np
+from .._utils import set_module
+from .numeric import uint8, ndarray, dtype
+
+__all__ = ['memmap']
+
+dtypedescr = dtype
+valid_filemodes = ["r", "c", "r+", "w+"]
+writeable_filemodes = ["r+", "w+"]
+
+mode_equivalents = {
+ "readonly":"r",
+ "copyonwrite":"c",
+ "readwrite":"r+",
+ "write":"w+"
+ }
+
+
+@set_module('numpy')
+class memmap(ndarray):
+ """Create a memory-map to an array stored in a *binary* file on disk.
+
+ Memory-mapped files are used for accessing small segments of large files
+ on disk, without reading the entire file into memory. NumPy's
+ memmap's are array-like objects. This differs from Python's ``mmap``
+ module, which uses file-like objects.
+
+ This subclass of ndarray has some unpleasant interactions with
+ some operations, because it doesn't quite fit properly as a subclass.
+ An alternative to using this subclass is to create the ``mmap``
+ object yourself, then create an ndarray with ndarray.__new__ directly,
+ passing the object created in its 'buffer=' parameter.
+
+ This class may at some point be turned into a factory function
+ which returns a view into an mmap buffer.
+
+ Flush the memmap instance to write the changes to the file. Currently there
+ is no API to close the underlying ``mmap``. It is tricky to ensure the
+ resource is actually closed, since it may be shared between different
+ memmap instances.
+
+
+ Parameters
+ ----------
+ filename : str, file-like object, or pathlib.Path instance
+ The file name or file object to be used as the array data buffer.
+ dtype : data-type, optional
+ The data-type used to interpret the file contents.
+ Default is `uint8`.
+ mode : {'r+', 'r', 'w+', 'c'}, optional
+ The file is opened in this mode:
+
+ +------+-------------------------------------------------------------+
+ | 'r' | Open existing file for reading only. |
+ +------+-------------------------------------------------------------+
+ | 'r+' | Open existing file for reading and writing. |
+ +------+-------------------------------------------------------------+
+ | 'w+' | Create or overwrite existing file for reading and writing. |
+ | | If ``mode == 'w+'`` then `shape` must also be specified. |
+ +------+-------------------------------------------------------------+
+ | 'c' | Copy-on-write: assignments affect data in memory, but |
+ | | changes are not saved to disk. The file on disk is |
+ | | read-only. |
+ +------+-------------------------------------------------------------+
+
+ Default is 'r+'.
+ offset : int, optional
+ In the file, array data starts at this offset. Since `offset` is
+ measured in bytes, it should normally be a multiple of the byte-size
+ of `dtype`. When ``mode != 'r'``, even positive offsets beyond end of
+ file are valid; The file will be extended to accommodate the
+ additional data. By default, ``memmap`` will start at the beginning of
+ the file, even if ``filename`` is a file pointer ``fp`` and
+ ``fp.tell() != 0``.
+ shape : int or sequence of ints, optional
+ The desired shape of the array. If ``mode == 'r'`` and the number
+ of remaining bytes after `offset` is not a multiple of the byte-size
+ of `dtype`, you must specify `shape`. By default, the returned array
+ will be 1-D with the number of elements determined by file size
+ and data-type.
+
+ .. versionchanged:: 2.0
+ The shape parameter can now be any integer sequence type, previously
+ types were limited to tuple and int.
+
+ order : {'C', 'F'}, optional
+ Specify the order of the ndarray memory layout:
+ :term:`row-major`, C-style or :term:`column-major`,
+ Fortran-style. This only has an effect if the shape is
+ greater than 1-D. The default order is 'C'.
+
+ Attributes
+ ----------
+ filename : str or pathlib.Path instance
+ Path to the mapped file.
+ offset : int
+ Offset position in the file.
+ mode : str
+ File mode.
+
+ Methods
+ -------
+ flush
+ Flush any changes in memory to file on disk.
+ When you delete a memmap object, flush is called first to write
+ changes to disk.
+
+
+ See also
+ --------
+ lib.format.open_memmap : Create or load a memory-mapped ``.npy`` file.
+
+ Notes
+ -----
+ The memmap object can be used anywhere an ndarray is accepted.
+ Given a memmap ``fp``, ``isinstance(fp, numpy.ndarray)`` returns
+ ``True``.
+
+ Memory-mapped files cannot be larger than 2GB on 32-bit systems.
+
+ When a memmap causes a file to be created or extended beyond its
+ current size in the filesystem, the contents of the new part are
+ unspecified. On systems with POSIX filesystem semantics, the extended
+ part will be filled with zero bytes.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> data = np.arange(12, dtype='float32')
+ >>> data.resize((3,4))
+
+ This example uses a temporary file so that doctest doesn't write
+ files to your directory. You would use a 'normal' filename.
+
+ >>> from tempfile import mkdtemp
+ >>> import os.path as path
+ >>> filename = path.join(mkdtemp(), 'newfile.dat')
+
+ Create a memmap with dtype and shape that matches our data:
+
+ >>> fp = np.memmap(filename, dtype='float32', mode='w+', shape=(3,4))
+ >>> fp
+ memmap([[0., 0., 0., 0.],
+ [0., 0., 0., 0.],
+ [0., 0., 0., 0.]], dtype=float32)
+
+ Write data to memmap array:
+
+ >>> fp[:] = data[:]
+ >>> fp
+ memmap([[ 0., 1., 2., 3.],
+ [ 4., 5., 6., 7.],
+ [ 8., 9., 10., 11.]], dtype=float32)
+
+ >>> fp.filename == path.abspath(filename)
+ True
+
+ Flushes memory changes to disk in order to read them back
+
+ >>> fp.flush()
+
+ Load the memmap and verify data was stored:
+
+ >>> newfp = np.memmap(filename, dtype='float32', mode='r', shape=(3,4))
+ >>> newfp
+ memmap([[ 0., 1., 2., 3.],
+ [ 4., 5., 6., 7.],
+ [ 8., 9., 10., 11.]], dtype=float32)
+
+ Read-only memmap:
+
+ >>> fpr = np.memmap(filename, dtype='float32', mode='r', shape=(3,4))
+ >>> fpr.flags.writeable
+ False
+
+ Copy-on-write memmap:
+
+ >>> fpc = np.memmap(filename, dtype='float32', mode='c', shape=(3,4))
+ >>> fpc.flags.writeable
+ True
+
+ It's possible to assign to copy-on-write array, but values are only
+ written into the memory copy of the array, and not written to disk:
+
+ >>> fpc
+ memmap([[ 0., 1., 2., 3.],
+ [ 4., 5., 6., 7.],
+ [ 8., 9., 10., 11.]], dtype=float32)
+ >>> fpc[0,:] = 0
+ >>> fpc
+ memmap([[ 0., 0., 0., 0.],
+ [ 4., 5., 6., 7.],
+ [ 8., 9., 10., 11.]], dtype=float32)
+
+ File on disk is unchanged:
+
+ >>> fpr
+ memmap([[ 0., 1., 2., 3.],
+ [ 4., 5., 6., 7.],
+ [ 8., 9., 10., 11.]], dtype=float32)
+
+ Offset into a memmap:
+
+ >>> fpo = np.memmap(filename, dtype='float32', mode='r', offset=16)
+ >>> fpo
+ memmap([ 4., 5., 6., 7., 8., 9., 10., 11.], dtype=float32)
+
+ """
+
+ __array_priority__ = -100.0
+
+ def __new__(subtype, filename, dtype=uint8, mode='r+', offset=0,
+ shape=None, order='C'):
+ # Import here to minimize 'import numpy' overhead
+ import mmap
+ import os.path
+ try:
+ mode = mode_equivalents[mode]
+ except KeyError as e:
+ if mode not in valid_filemodes:
+ raise ValueError(
+ "mode must be one of {!r} (got {!r})"
+ .format(valid_filemodes + list(mode_equivalents.keys()), mode)
+ ) from None
+
+ if mode == 'w+' and shape is None:
+ raise ValueError("shape must be given if mode == 'w+'")
+
+ if hasattr(filename, 'read'):
+ f_ctx = nullcontext(filename)
+ else:
+ f_ctx = open(
+ os.fspath(filename),
+ ('r' if mode == 'c' else mode)+'b'
+ )
+
+ with f_ctx as fid:
+ fid.seek(0, 2)
+ flen = fid.tell()
+ descr = dtypedescr(dtype)
+ _dbytes = descr.itemsize
+
+ if shape is None:
+ bytes = flen - offset
+ if bytes % _dbytes:
+ raise ValueError("Size of available data is not a "
+ "multiple of the data-type size.")
+ size = bytes // _dbytes
+ shape = (size,)
+ else:
+ if type(shape) not in (tuple, list):
+ try:
+ shape = [operator.index(shape)]
+ except TypeError:
+ pass
+ shape = tuple(shape)
+ size = np.intp(1) # avoid default choice of np.int_, which might overflow
+ for k in shape:
+ size *= k
+
+ bytes = int(offset + size*_dbytes)
+
+ if mode in ('w+', 'r+'):
+ # gh-27723
+ # if bytes == 0, we write out 1 byte to allow empty memmap.
+ bytes = max(bytes, 1)
+ if flen < bytes:
+ fid.seek(bytes - 1, 0)
+ fid.write(b'\0')
+ fid.flush()
+
+ if mode == 'c':
+ acc = mmap.ACCESS_COPY
+ elif mode == 'r':
+ acc = mmap.ACCESS_READ
+ else:
+ acc = mmap.ACCESS_WRITE
+
+ start = offset - offset % mmap.ALLOCATIONGRANULARITY
+ bytes -= start
+ # bytes == 0 is problematic as in mmap length=0 maps the full file.
+ # See PR gh-27723 for a more detailed explanation.
+ if bytes == 0 and start > 0:
+ bytes += mmap.ALLOCATIONGRANULARITY
+ start -= mmap.ALLOCATIONGRANULARITY
+ array_offset = offset - start
+ mm = mmap.mmap(fid.fileno(), bytes, access=acc, offset=start)
+
+ self = ndarray.__new__(subtype, shape, dtype=descr, buffer=mm,
+ offset=array_offset, order=order)
+ self._mmap = mm
+ self.offset = offset
+ self.mode = mode
+
+ if isinstance(filename, os.PathLike):
+ # special case - if we were constructed with a pathlib.path,
+ # then filename is a path object, not a string
+ self.filename = filename.resolve()
+ elif hasattr(fid, "name") and isinstance(fid.name, str):
+ # py3 returns int for TemporaryFile().name
+ self.filename = os.path.abspath(fid.name)
+ # same as memmap copies (e.g. memmap + 1)
+ else:
+ self.filename = None
+
+ return self
+
+ def __array_finalize__(self, obj):
+ if hasattr(obj, '_mmap') and np.may_share_memory(self, obj):
+ self._mmap = obj._mmap
+ self.filename = obj.filename
+ self.offset = obj.offset
+ self.mode = obj.mode
+ else:
+ self._mmap = None
+ self.filename = None
+ self.offset = None
+ self.mode = None
+
+ def flush(self):
+ """
+ Write any changes in the array to the file on disk.
+
+ For further information, see `memmap`.
+
+ Parameters
+ ----------
+ None
+
+ See Also
+ --------
+ memmap
+
+ """
+ if self.base is not None and hasattr(self.base, 'flush'):
+ self.base.flush()
+
+ def __array_wrap__(self, arr, context=None, return_scalar=False):
+ arr = super().__array_wrap__(arr, context)
+
+ # Return a memmap if a memmap was given as the output of the
+ # ufunc. Leave the arr class unchanged if self is not a memmap
+ # to keep original memmap subclasses behavior
+ if self is arr or type(self) is not memmap:
+ return arr
+
+ # Return scalar instead of 0d memmap, e.g. for np.sum with
+ # axis=None (note that subclasses will not reach here)
+ if return_scalar:
+ return arr[()]
+
+ # Return ndarray otherwise
+ return arr.view(np.ndarray)
+
+ def __getitem__(self, index):
+ res = super().__getitem__(index)
+ if type(res) is memmap and res._mmap is None:
+ return res.view(type=ndarray)
+ return res
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/memmap.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/memmap.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..0b31328404fb397614bd03832af9282ce251c4f4
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/memmap.pyi
@@ -0,0 +1,3 @@
+from numpy import memmap
+
+__all__ = ["memmap"]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/multiarray.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/multiarray.py
new file mode 100644
index 0000000000000000000000000000000000000000..088de1073e7ecb6ded523ec82482be658f97fb2c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/multiarray.py
@@ -0,0 +1,1754 @@
+"""
+Create the numpy._core.multiarray namespace for backward compatibility.
+In v1.16 the multiarray and umath c-extension modules were merged into
+a single _multiarray_umath extension module. So we replicate the old
+namespace by importing from the extension module.
+
+"""
+
+import functools
+from . import overrides
+from . import _multiarray_umath
+from ._multiarray_umath import * # noqa: F403
+# These imports are needed for backward compatibility,
+# do not change them. issue gh-15518
+# _get_ndarray_c_version is semi-public, on purpose not added to __all__
+from ._multiarray_umath import (
+ _flagdict, from_dlpack, _place, _reconstruct,
+ _vec_string, _ARRAY_API, _monotonicity, _get_ndarray_c_version,
+ _get_madvise_hugepage, _set_madvise_hugepage,
+ )
+
+__all__ = [
+ '_ARRAY_API', 'ALLOW_THREADS', 'BUFSIZE', 'CLIP', 'DATETIMEUNITS',
+ 'ITEM_HASOBJECT', 'ITEM_IS_POINTER', 'LIST_PICKLE', 'MAXDIMS',
+ 'MAY_SHARE_BOUNDS', 'MAY_SHARE_EXACT', 'NEEDS_INIT', 'NEEDS_PYAPI',
+ 'RAISE', 'USE_GETITEM', 'USE_SETITEM', 'WRAP',
+ '_flagdict', 'from_dlpack', '_place', '_reconstruct', '_vec_string',
+ '_monotonicity', 'add_docstring', 'arange', 'array', 'asarray',
+ 'asanyarray', 'ascontiguousarray', 'asfortranarray', 'bincount',
+ 'broadcast', 'busday_count', 'busday_offset', 'busdaycalendar', 'can_cast',
+ 'compare_chararrays', 'concatenate', 'copyto', 'correlate', 'correlate2',
+ 'count_nonzero', 'c_einsum', 'datetime_as_string', 'datetime_data',
+ 'dot', 'dragon4_positional', 'dragon4_scientific', 'dtype',
+ 'empty', 'empty_like', 'error', 'flagsobj', 'flatiter', 'format_longfloat',
+ 'frombuffer', 'fromfile', 'fromiter', 'fromstring',
+ 'get_handler_name', 'get_handler_version', 'inner', 'interp',
+ 'interp_complex', 'is_busday', 'lexsort', 'matmul', 'vecdot',
+ 'may_share_memory', 'min_scalar_type', 'ndarray', 'nditer', 'nested_iters',
+ 'normalize_axis_index', 'packbits', 'promote_types', 'putmask',
+ 'ravel_multi_index', 'result_type', 'scalar', 'set_datetimeparse_function',
+ 'set_typeDict', 'shares_memory', 'typeinfo',
+ 'unpackbits', 'unravel_index', 'vdot', 'where', 'zeros']
+
+# For backward compatibility, make sure pickle imports
+# these functions from here
+_reconstruct.__module__ = 'numpy._core.multiarray'
+scalar.__module__ = 'numpy._core.multiarray'
+
+
+from_dlpack.__module__ = 'numpy'
+arange.__module__ = 'numpy'
+array.__module__ = 'numpy'
+asarray.__module__ = 'numpy'
+asanyarray.__module__ = 'numpy'
+ascontiguousarray.__module__ = 'numpy'
+asfortranarray.__module__ = 'numpy'
+datetime_data.__module__ = 'numpy'
+empty.__module__ = 'numpy'
+frombuffer.__module__ = 'numpy'
+fromfile.__module__ = 'numpy'
+fromiter.__module__ = 'numpy'
+frompyfunc.__module__ = 'numpy'
+fromstring.__module__ = 'numpy'
+may_share_memory.__module__ = 'numpy'
+nested_iters.__module__ = 'numpy'
+promote_types.__module__ = 'numpy'
+zeros.__module__ = 'numpy'
+normalize_axis_index.__module__ = 'numpy.lib.array_utils'
+add_docstring.__module__ = 'numpy.lib'
+compare_chararrays.__module__ = 'numpy.char'
+
+
+def _override___module__():
+ namespace_names = globals()
+ for ufunc_name in [
+ 'absolute', 'arccos', 'arccosh', 'add', 'arcsin', 'arcsinh', 'arctan',
+ 'arctan2', 'arctanh', 'bitwise_and', 'bitwise_count', 'invert',
+ 'left_shift', 'bitwise_or', 'right_shift', 'bitwise_xor', 'cbrt',
+ 'ceil', 'conjugate', 'copysign', 'cos', 'cosh', 'deg2rad', 'degrees',
+ 'divide', 'divmod', 'equal', 'exp', 'exp2', 'expm1', 'fabs',
+ 'float_power', 'floor', 'floor_divide', 'fmax', 'fmin', 'fmod',
+ 'frexp', 'gcd', 'greater', 'greater_equal', 'heaviside', 'hypot',
+ 'isfinite', 'isinf', 'isnan', 'isnat', 'lcm', 'ldexp', 'less',
+ 'less_equal', 'log', 'log10', 'log1p', 'log2', 'logaddexp',
+ 'logaddexp2', 'logical_and', 'logical_not', 'logical_or',
+ 'logical_xor', 'matmul', 'matvec', 'maximum', 'minimum', 'remainder',
+ 'modf', 'multiply', 'negative', 'nextafter', 'not_equal', 'positive',
+ 'power', 'rad2deg', 'radians', 'reciprocal', 'rint', 'sign', 'signbit',
+ 'sin', 'sinh', 'spacing', 'sqrt', 'square', 'subtract', 'tan', 'tanh',
+ 'trunc', 'vecdot', 'vecmat',
+ ]:
+ ufunc = namespace_names[ufunc_name]
+ ufunc.__module__ = "numpy"
+ ufunc.__qualname__ = ufunc_name
+
+
+_override___module__()
+
+
+# We can't verify dispatcher signatures because NumPy's C functions don't
+# support introspection.
+array_function_from_c_func_and_dispatcher = functools.partial(
+ overrides.array_function_from_dispatcher,
+ module='numpy', docs_from_dispatcher=True, verify=False)
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.empty_like)
+def empty_like(
+ prototype, dtype=None, order=None, subok=None, shape=None, *, device=None
+):
+ """
+ empty_like(prototype, dtype=None, order='K', subok=True, shape=None, *,
+ device=None)
+
+ Return a new array with the same shape and type as a given array.
+
+ Parameters
+ ----------
+ prototype : array_like
+ The shape and data-type of `prototype` define these same attributes
+ of the returned array.
+ dtype : data-type, optional
+ Overrides the data type of the result.
+ order : {'C', 'F', 'A', or 'K'}, optional
+ Overrides the memory layout of the result. 'C' means C-order,
+ 'F' means F-order, 'A' means 'F' if `prototype` is Fortran
+ contiguous, 'C' otherwise. 'K' means match the layout of `prototype`
+ as closely as possible.
+ subok : bool, optional.
+ If True, then the newly created array will use the sub-class
+ type of `prototype`, otherwise it will be a base-class array. Defaults
+ to True.
+ shape : int or sequence of ints, optional.
+ Overrides the shape of the result. If order='K' and the number of
+ dimensions is unchanged, will try to keep order, otherwise,
+ order='C' is implied.
+ device : str, optional
+ The device on which to place the created array. Default: None.
+ For Array-API interoperability only, so must be ``"cpu"`` if passed.
+
+ .. versionadded:: 2.0.0
+
+ Returns
+ -------
+ out : ndarray
+ Array of uninitialized (arbitrary) data with the same
+ shape and type as `prototype`.
+
+ See Also
+ --------
+ ones_like : Return an array of ones with shape and type of input.
+ zeros_like : Return an array of zeros with shape and type of input.
+ full_like : Return a new array with shape of input filled with value.
+ empty : Return a new uninitialized array.
+
+ Notes
+ -----
+ Unlike other array creation functions (e.g. `zeros_like`, `ones_like`,
+ `full_like`), `empty_like` does not initialize the values of the array,
+ and may therefore be marginally faster. However, the values stored in the
+ newly allocated array are arbitrary. For reproducible behavior, be sure
+ to set each element of the array before reading.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = ([1,2,3], [4,5,6]) # a is array-like
+ >>> np.empty_like(a)
+ array([[-1073741821, -1073741821, 3], # uninitialized
+ [ 0, 0, -1073741821]])
+ >>> a = np.array([[1., 2., 3.],[4.,5.,6.]])
+ >>> np.empty_like(a)
+ array([[ -2.00000715e+000, 1.48219694e-323, -2.00000572e+000], # uninitialized
+ [ 4.38791518e-305, -2.00000715e+000, 4.17269252e-309]])
+
+ """ # NOQA
+ return (prototype,)
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.concatenate)
+def concatenate(arrays, axis=None, out=None, *, dtype=None, casting=None):
+ """
+ concatenate(
+ (a1, a2, ...),
+ axis=0,
+ out=None,
+ dtype=None,
+ casting="same_kind"
+ )
+
+ Join a sequence of arrays along an existing axis.
+
+ Parameters
+ ----------
+ a1, a2, ... : sequence of array_like
+ The arrays must have the same shape, except in the dimension
+ corresponding to `axis` (the first, by default).
+ axis : int, optional
+ The axis along which the arrays will be joined. If axis is None,
+ arrays are flattened before use. Default is 0.
+ out : ndarray, optional
+ If provided, the destination to place the result. The shape must be
+ correct, matching that of what concatenate would have returned if no
+ out argument were specified.
+ dtype : str or dtype
+ If provided, the destination array will have this dtype. Cannot be
+ provided together with `out`.
+
+ .. versionadded:: 1.20.0
+
+ casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
+ Controls what kind of data casting may occur. Defaults to 'same_kind'.
+ For a description of the options, please see :term:`casting`.
+
+ .. versionadded:: 1.20.0
+
+ Returns
+ -------
+ res : ndarray
+ The concatenated array.
+
+ See Also
+ --------
+ ma.concatenate : Concatenate function that preserves input masks.
+ array_split : Split an array into multiple sub-arrays of equal or
+ near-equal size.
+ split : Split array into a list of multiple sub-arrays of equal size.
+ hsplit : Split array into multiple sub-arrays horizontally (column wise).
+ vsplit : Split array into multiple sub-arrays vertically (row wise).
+ dsplit : Split array into multiple sub-arrays along the 3rd axis (depth).
+ stack : Stack a sequence of arrays along a new axis.
+ block : Assemble arrays from blocks.
+ hstack : Stack arrays in sequence horizontally (column wise).
+ vstack : Stack arrays in sequence vertically (row wise).
+ dstack : Stack arrays in sequence depth wise (along third dimension).
+ column_stack : Stack 1-D arrays as columns into a 2-D array.
+
+ Notes
+ -----
+ When one or more of the arrays to be concatenated is a MaskedArray,
+ this function will return a MaskedArray object instead of an ndarray,
+ but the input masks are *not* preserved. In cases where a MaskedArray
+ is expected as input, use the ma.concatenate function from the masked
+ array module instead.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[1, 2], [3, 4]])
+ >>> b = np.array([[5, 6]])
+ >>> np.concatenate((a, b), axis=0)
+ array([[1, 2],
+ [3, 4],
+ [5, 6]])
+ >>> np.concatenate((a, b.T), axis=1)
+ array([[1, 2, 5],
+ [3, 4, 6]])
+ >>> np.concatenate((a, b), axis=None)
+ array([1, 2, 3, 4, 5, 6])
+
+ This function will not preserve masking of MaskedArray inputs.
+
+ >>> a = np.ma.arange(3)
+ >>> a[1] = np.ma.masked
+ >>> b = np.arange(2, 5)
+ >>> a
+ masked_array(data=[0, --, 2],
+ mask=[False, True, False],
+ fill_value=999999)
+ >>> b
+ array([2, 3, 4])
+ >>> np.concatenate([a, b])
+ masked_array(data=[0, 1, 2, 2, 3, 4],
+ mask=False,
+ fill_value=999999)
+ >>> np.ma.concatenate([a, b])
+ masked_array(data=[0, --, 2, 2, 3, 4],
+ mask=[False, True, False, False, False, False],
+ fill_value=999999)
+
+ """
+ if out is not None:
+ # optimize for the typical case where only arrays is provided
+ arrays = list(arrays)
+ arrays.append(out)
+ return arrays
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.inner)
+def inner(a, b):
+ """
+ inner(a, b, /)
+
+ Inner product of two arrays.
+
+ Ordinary inner product of vectors for 1-D arrays (without complex
+ conjugation), in higher dimensions a sum product over the last axes.
+
+ Parameters
+ ----------
+ a, b : array_like
+ If `a` and `b` are nonscalar, their last dimensions must match.
+
+ Returns
+ -------
+ out : ndarray
+ If `a` and `b` are both
+ scalars or both 1-D arrays then a scalar is returned; otherwise
+ an array is returned.
+ ``out.shape = (*a.shape[:-1], *b.shape[:-1])``
+
+ Raises
+ ------
+ ValueError
+ If both `a` and `b` are nonscalar and their last dimensions have
+ different sizes.
+
+ See Also
+ --------
+ tensordot : Sum products over arbitrary axes.
+ dot : Generalised matrix product, using second last dimension of `b`.
+ vecdot : Vector dot product of two arrays.
+ einsum : Einstein summation convention.
+
+ Notes
+ -----
+ For vectors (1-D arrays) it computes the ordinary inner-product::
+
+ np.inner(a, b) = sum(a[:]*b[:])
+
+ More generally, if ``ndim(a) = r > 0`` and ``ndim(b) = s > 0``::
+
+ np.inner(a, b) = np.tensordot(a, b, axes=(-1,-1))
+
+ or explicitly::
+
+ np.inner(a, b)[i0,...,ir-2,j0,...,js-2]
+ = sum(a[i0,...,ir-2,:]*b[j0,...,js-2,:])
+
+ In addition `a` or `b` may be scalars, in which case::
+
+ np.inner(a,b) = a*b
+
+ Examples
+ --------
+ Ordinary inner product for vectors:
+
+ >>> import numpy as np
+ >>> a = np.array([1,2,3])
+ >>> b = np.array([0,1,0])
+ >>> np.inner(a, b)
+ 2
+
+ Some multidimensional examples:
+
+ >>> a = np.arange(24).reshape((2,3,4))
+ >>> b = np.arange(4)
+ >>> c = np.inner(a, b)
+ >>> c.shape
+ (2, 3)
+ >>> c
+ array([[ 14, 38, 62],
+ [ 86, 110, 134]])
+
+ >>> a = np.arange(2).reshape((1,1,2))
+ >>> b = np.arange(6).reshape((3,2))
+ >>> c = np.inner(a, b)
+ >>> c.shape
+ (1, 1, 3)
+ >>> c
+ array([[[1, 3, 5]]])
+
+ An example where `b` is a scalar:
+
+ >>> np.inner(np.eye(2), 7)
+ array([[7., 0.],
+ [0., 7.]])
+
+ """
+ return (a, b)
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.where)
+def where(condition, x=None, y=None):
+ """
+ where(condition, [x, y], /)
+
+ Return elements chosen from `x` or `y` depending on `condition`.
+
+ .. note::
+ When only `condition` is provided, this function is a shorthand for
+ ``np.asarray(condition).nonzero()``. Using `nonzero` directly should be
+ preferred, as it behaves correctly for subclasses. The rest of this
+ documentation covers only the case where all three arguments are
+ provided.
+
+ Parameters
+ ----------
+ condition : array_like, bool
+ Where True, yield `x`, otherwise yield `y`.
+ x, y : array_like
+ Values from which to choose. `x`, `y` and `condition` need to be
+ broadcastable to some shape.
+
+ Returns
+ -------
+ out : ndarray
+ An array with elements from `x` where `condition` is True, and elements
+ from `y` elsewhere.
+
+ See Also
+ --------
+ choose
+ nonzero : The function that is called when x and y are omitted
+
+ Notes
+ -----
+ If all the arrays are 1-D, `where` is equivalent to::
+
+ [xv if c else yv
+ for c, xv, yv in zip(condition, x, y)]
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.arange(10)
+ >>> a
+ array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
+ >>> np.where(a < 5, a, 10*a)
+ array([ 0, 1, 2, 3, 4, 50, 60, 70, 80, 90])
+
+ This can be used on multidimensional arrays too:
+
+ >>> np.where([[True, False], [True, True]],
+ ... [[1, 2], [3, 4]],
+ ... [[9, 8], [7, 6]])
+ array([[1, 8],
+ [3, 4]])
+
+ The shapes of x, y, and the condition are broadcast together:
+
+ >>> x, y = np.ogrid[:3, :4]
+ >>> np.where(x < y, x, 10 + y) # both x and 10+y are broadcast
+ array([[10, 0, 0, 0],
+ [10, 11, 1, 1],
+ [10, 11, 12, 2]])
+
+ >>> a = np.array([[0, 1, 2],
+ ... [0, 2, 4],
+ ... [0, 3, 6]])
+ >>> np.where(a < 4, a, -1) # -1 is broadcast
+ array([[ 0, 1, 2],
+ [ 0, 2, -1],
+ [ 0, 3, -1]])
+ """
+ return (condition, x, y)
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.lexsort)
+def lexsort(keys, axis=None):
+ """
+ lexsort(keys, axis=-1)
+
+ Perform an indirect stable sort using a sequence of keys.
+
+ Given multiple sorting keys, lexsort returns an array of integer indices
+ that describes the sort order by multiple keys. The last key in the
+ sequence is used for the primary sort order, ties are broken by the
+ second-to-last key, and so on.
+
+ Parameters
+ ----------
+ keys : (k, m, n, ...) array-like
+ The `k` keys to be sorted. The *last* key (e.g, the last
+ row if `keys` is a 2D array) is the primary sort key.
+ Each element of `keys` along the zeroth axis must be
+ an array-like object of the same shape.
+ axis : int, optional
+ Axis to be indirectly sorted. By default, sort over the last axis
+ of each sequence. Separate slices along `axis` sorted over
+ independently; see last example.
+
+ Returns
+ -------
+ indices : (m, n, ...) ndarray of ints
+ Array of indices that sort the keys along the specified axis.
+
+ See Also
+ --------
+ argsort : Indirect sort.
+ ndarray.sort : In-place sort.
+ sort : Return a sorted copy of an array.
+
+ Examples
+ --------
+ Sort names: first by surname, then by name.
+
+ >>> import numpy as np
+ >>> surnames = ('Hertz', 'Galilei', 'Hertz')
+ >>> first_names = ('Heinrich', 'Galileo', 'Gustav')
+ >>> ind = np.lexsort((first_names, surnames))
+ >>> ind
+ array([1, 2, 0])
+
+ >>> [surnames[i] + ", " + first_names[i] for i in ind]
+ ['Galilei, Galileo', 'Hertz, Gustav', 'Hertz, Heinrich']
+
+ Sort according to two numerical keys, first by elements
+ of ``a``, then breaking ties according to elements of ``b``:
+
+ >>> a = [1, 5, 1, 4, 3, 4, 4] # First sequence
+ >>> b = [9, 4, 0, 4, 0, 2, 1] # Second sequence
+ >>> ind = np.lexsort((b, a)) # Sort by `a`, then by `b`
+ >>> ind
+ array([2, 0, 4, 6, 5, 3, 1])
+ >>> [(a[i], b[i]) for i in ind]
+ [(1, 0), (1, 9), (3, 0), (4, 1), (4, 2), (4, 4), (5, 4)]
+
+ Compare against `argsort`, which would sort each key independently.
+
+ >>> np.argsort((b, a), kind='stable')
+ array([[2, 4, 6, 5, 1, 3, 0],
+ [0, 2, 4, 3, 5, 6, 1]])
+
+ To sort lexicographically with `argsort`, we would need to provide a
+ structured array.
+
+ >>> x = np.array([(ai, bi) for ai, bi in zip(a, b)],
+ ... dtype = np.dtype([('x', int), ('y', int)]))
+ >>> np.argsort(x) # or np.argsort(x, order=('x', 'y'))
+ array([2, 0, 4, 6, 5, 3, 1])
+
+ The zeroth axis of `keys` always corresponds with the sequence of keys,
+ so 2D arrays are treated just like other sequences of keys.
+
+ >>> arr = np.asarray([b, a])
+ >>> ind2 = np.lexsort(arr)
+ >>> np.testing.assert_equal(ind2, ind)
+
+ Accordingly, the `axis` parameter refers to an axis of *each* key, not of
+ the `keys` argument itself. For instance, the array ``arr`` is treated as
+ a sequence of two 1-D keys, so specifying ``axis=0`` is equivalent to
+ using the default axis, ``axis=-1``.
+
+ >>> np.testing.assert_equal(np.lexsort(arr, axis=0),
+ ... np.lexsort(arr, axis=-1))
+
+ For higher-dimensional arrays, the axis parameter begins to matter. The
+ resulting array has the same shape as each key, and the values are what
+ we would expect if `lexsort` were performed on corresponding slices
+ of the keys independently. For instance,
+
+ >>> x = [[1, 2, 3, 4],
+ ... [4, 3, 2, 1],
+ ... [2, 1, 4, 3]]
+ >>> y = [[2, 2, 1, 1],
+ ... [1, 2, 1, 2],
+ ... [1, 1, 2, 1]]
+ >>> np.lexsort((x, y), axis=1)
+ array([[2, 3, 0, 1],
+ [2, 0, 3, 1],
+ [1, 0, 3, 2]])
+
+ Each row of the result is what we would expect if we were to perform
+ `lexsort` on the corresponding row of the keys:
+
+ >>> for i in range(3):
+ ... print(np.lexsort((x[i], y[i])))
+ [2 3 0 1]
+ [2 0 3 1]
+ [1 0 3 2]
+
+ """
+ if isinstance(keys, tuple):
+ return keys
+ else:
+ return (keys,)
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.can_cast)
+def can_cast(from_, to, casting=None):
+ """
+ can_cast(from_, to, casting='safe')
+
+ Returns True if cast between data types can occur according to the
+ casting rule.
+
+ Parameters
+ ----------
+ from_ : dtype, dtype specifier, NumPy scalar, or array
+ Data type, NumPy scalar, or array to cast from.
+ to : dtype or dtype specifier
+ Data type to cast to.
+ casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
+ Controls what kind of data casting may occur.
+
+ * 'no' means the data types should not be cast at all.
+ * 'equiv' means only byte-order changes are allowed.
+ * 'safe' means only casts which can preserve values are allowed.
+ * 'same_kind' means only safe casts or casts within a kind,
+ like float64 to float32, are allowed.
+ * 'unsafe' means any data conversions may be done.
+
+ Returns
+ -------
+ out : bool
+ True if cast can occur according to the casting rule.
+
+ Notes
+ -----
+ .. versionchanged:: 2.0
+ This function does not support Python scalars anymore and does not
+ apply any value-based logic for 0-D arrays and NumPy scalars.
+
+ See also
+ --------
+ dtype, result_type
+
+ Examples
+ --------
+ Basic examples
+
+ >>> import numpy as np
+ >>> np.can_cast(np.int32, np.int64)
+ True
+ >>> np.can_cast(np.float64, complex)
+ True
+ >>> np.can_cast(complex, float)
+ False
+
+ >>> np.can_cast('i8', 'f8')
+ True
+ >>> np.can_cast('i8', 'f4')
+ False
+ >>> np.can_cast('i4', 'S4')
+ False
+
+ """
+ return (from_,)
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.min_scalar_type)
+def min_scalar_type(a):
+ """
+ min_scalar_type(a, /)
+
+ For scalar ``a``, returns the data type with the smallest size
+ and smallest scalar kind which can hold its value. For non-scalar
+ array ``a``, returns the vector's dtype unmodified.
+
+ Floating point values are not demoted to integers,
+ and complex values are not demoted to floats.
+
+ Parameters
+ ----------
+ a : scalar or array_like
+ The value whose minimal data type is to be found.
+
+ Returns
+ -------
+ out : dtype
+ The minimal data type.
+
+ See Also
+ --------
+ result_type, promote_types, dtype, can_cast
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.min_scalar_type(10)
+ dtype('uint8')
+
+ >>> np.min_scalar_type(-260)
+ dtype('int16')
+
+ >>> np.min_scalar_type(3.1)
+ dtype('float16')
+
+ >>> np.min_scalar_type(1e50)
+ dtype('float64')
+
+ >>> np.min_scalar_type(np.arange(4,dtype='f8'))
+ dtype('float64')
+
+ """
+ return (a,)
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.result_type)
+def result_type(*arrays_and_dtypes):
+ """
+ result_type(*arrays_and_dtypes)
+
+ Returns the type that results from applying the NumPy
+ type promotion rules to the arguments.
+
+ Type promotion in NumPy works similarly to the rules in languages
+ like C++, with some slight differences. When both scalars and
+ arrays are used, the array's type takes precedence and the actual value
+ of the scalar is taken into account.
+
+ For example, calculating 3*a, where a is an array of 32-bit floats,
+ intuitively should result in a 32-bit float output. If the 3 is a
+ 32-bit integer, the NumPy rules indicate it can't convert losslessly
+ into a 32-bit float, so a 64-bit float should be the result type.
+ By examining the value of the constant, '3', we see that it fits in
+ an 8-bit integer, which can be cast losslessly into the 32-bit float.
+
+ Parameters
+ ----------
+ arrays_and_dtypes : list of arrays and dtypes
+ The operands of some operation whose result type is needed.
+
+ Returns
+ -------
+ out : dtype
+ The result type.
+
+ See also
+ --------
+ dtype, promote_types, min_scalar_type, can_cast
+
+ Notes
+ -----
+ The specific algorithm used is as follows.
+
+ Categories are determined by first checking which of boolean,
+ integer (int/uint), or floating point (float/complex) the maximum
+ kind of all the arrays and the scalars are.
+
+ If there are only scalars or the maximum category of the scalars
+ is higher than the maximum category of the arrays,
+ the data types are combined with :func:`promote_types`
+ to produce the return value.
+
+ Otherwise, `min_scalar_type` is called on each scalar, and
+ the resulting data types are all combined with :func:`promote_types`
+ to produce the return value.
+
+ The set of int values is not a subset of the uint values for types
+ with the same number of bits, something not reflected in
+ :func:`min_scalar_type`, but handled as a special case in `result_type`.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.result_type(3, np.arange(7, dtype='i1'))
+ dtype('int8')
+
+ >>> np.result_type('i4', 'c8')
+ dtype('complex128')
+
+ >>> np.result_type(3.0, -2)
+ dtype('float64')
+
+ """
+ return arrays_and_dtypes
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.dot)
+def dot(a, b, out=None):
+ """
+ dot(a, b, out=None)
+
+ Dot product of two arrays. Specifically,
+
+ - If both `a` and `b` are 1-D arrays, it is inner product of vectors
+ (without complex conjugation).
+
+ - If both `a` and `b` are 2-D arrays, it is matrix multiplication,
+ but using :func:`matmul` or ``a @ b`` is preferred.
+
+ - If either `a` or `b` is 0-D (scalar), it is equivalent to
+ :func:`multiply` and using ``numpy.multiply(a, b)`` or ``a * b`` is
+ preferred.
+
+ - If `a` is an N-D array and `b` is a 1-D array, it is a sum product over
+ the last axis of `a` and `b`.
+
+ - If `a` is an N-D array and `b` is an M-D array (where ``M>=2``), it is a
+ sum product over the last axis of `a` and the second-to-last axis of
+ `b`::
+
+ dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])
+
+ It uses an optimized BLAS library when possible (see `numpy.linalg`).
+
+ Parameters
+ ----------
+ a : array_like
+ First argument.
+ b : array_like
+ Second argument.
+ out : ndarray, optional
+ Output argument. This must have the exact kind that would be returned
+ if it was not used. In particular, it must have the right type, must be
+ C-contiguous, and its dtype must be the dtype that would be returned
+ for `dot(a,b)`. This is a performance feature. Therefore, if these
+ conditions are not met, an exception is raised, instead of attempting
+ to be flexible.
+
+ Returns
+ -------
+ output : ndarray
+ Returns the dot product of `a` and `b`. If `a` and `b` are both
+ scalars or both 1-D arrays then a scalar is returned; otherwise
+ an array is returned.
+ If `out` is given, then it is returned.
+
+ Raises
+ ------
+ ValueError
+ If the last dimension of `a` is not the same size as
+ the second-to-last dimension of `b`.
+
+ See Also
+ --------
+ vdot : Complex-conjugating dot product.
+ vecdot : Vector dot product of two arrays.
+ tensordot : Sum products over arbitrary axes.
+ einsum : Einstein summation convention.
+ matmul : '@' operator as method with out parameter.
+ linalg.multi_dot : Chained dot product.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.dot(3, 4)
+ 12
+
+ Neither argument is complex-conjugated:
+
+ >>> np.dot([2j, 3j], [2j, 3j])
+ (-13+0j)
+
+ For 2-D arrays it is the matrix product:
+
+ >>> a = [[1, 0], [0, 1]]
+ >>> b = [[4, 1], [2, 2]]
+ >>> np.dot(a, b)
+ array([[4, 1],
+ [2, 2]])
+
+ >>> a = np.arange(3*4*5*6).reshape((3,4,5,6))
+ >>> b = np.arange(3*4*5*6)[::-1].reshape((5,4,6,3))
+ >>> np.dot(a, b)[2,3,2,1,2,2]
+ 499128
+ >>> sum(a[2,3,2,:] * b[1,2,:,2])
+ 499128
+
+ """
+ return (a, b, out)
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.vdot)
+def vdot(a, b):
+ r"""
+ vdot(a, b, /)
+
+ Return the dot product of two vectors.
+
+ The `vdot` function handles complex numbers differently than `dot`:
+ if the first argument is complex, it is replaced by its complex conjugate
+ in the dot product calculation. `vdot` also handles multidimensional
+ arrays differently than `dot`: it does not perform a matrix product, but
+ flattens the arguments to 1-D arrays before taking a vector dot product.
+
+ Consequently, when the arguments are 2-D arrays of the same shape, this
+ function effectively returns their
+ `Frobenius inner product `_
+ (also known as the *trace inner product* or the *standard inner product*
+ on a vector space of matrices).
+
+ Parameters
+ ----------
+ a : array_like
+ If `a` is complex the complex conjugate is taken before calculation
+ of the dot product.
+ b : array_like
+ Second argument to the dot product.
+
+ Returns
+ -------
+ output : ndarray
+ Dot product of `a` and `b`. Can be an int, float, or
+ complex depending on the types of `a` and `b`.
+
+ See Also
+ --------
+ dot : Return the dot product without using the complex conjugate of the
+ first argument.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([1+2j,3+4j])
+ >>> b = np.array([5+6j,7+8j])
+ >>> np.vdot(a, b)
+ (70-8j)
+ >>> np.vdot(b, a)
+ (70+8j)
+
+ Note that higher-dimensional arrays are flattened!
+
+ >>> a = np.array([[1, 4], [5, 6]])
+ >>> b = np.array([[4, 1], [2, 2]])
+ >>> np.vdot(a, b)
+ 30
+ >>> np.vdot(b, a)
+ 30
+ >>> 1*4 + 4*1 + 5*2 + 6*2
+ 30
+
+ """ # noqa: E501
+ return (a, b)
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.bincount)
+def bincount(x, weights=None, minlength=None):
+ """
+ bincount(x, /, weights=None, minlength=0)
+
+ Count number of occurrences of each value in array of non-negative ints.
+
+ The number of bins (of size 1) is one larger than the largest value in
+ `x`. If `minlength` is specified, there will be at least this number
+ of bins in the output array (though it will be longer if necessary,
+ depending on the contents of `x`).
+ Each bin gives the number of occurrences of its index value in `x`.
+ If `weights` is specified the input array is weighted by it, i.e. if a
+ value ``n`` is found at position ``i``, ``out[n] += weight[i]`` instead
+ of ``out[n] += 1``.
+
+ Parameters
+ ----------
+ x : array_like, 1 dimension, nonnegative ints
+ Input array.
+ weights : array_like, optional
+ Weights, array of the same shape as `x`.
+ minlength : int, optional
+ A minimum number of bins for the output array.
+
+ Returns
+ -------
+ out : ndarray of ints
+ The result of binning the input array.
+ The length of `out` is equal to ``np.amax(x)+1``.
+
+ Raises
+ ------
+ ValueError
+ If the input is not 1-dimensional, or contains elements with negative
+ values, or if `minlength` is negative.
+ TypeError
+ If the type of the input is float or complex.
+
+ See Also
+ --------
+ histogram, digitize, unique
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.bincount(np.arange(5))
+ array([1, 1, 1, 1, 1])
+ >>> np.bincount(np.array([0, 1, 1, 3, 2, 1, 7]))
+ array([1, 3, 1, 1, 0, 0, 0, 1])
+
+ >>> x = np.array([0, 1, 1, 3, 2, 1, 7, 23])
+ >>> np.bincount(x).size == np.amax(x)+1
+ True
+
+ The input array needs to be of integer dtype, otherwise a
+ TypeError is raised:
+
+ >>> np.bincount(np.arange(5, dtype=float))
+ Traceback (most recent call last):
+ ...
+ TypeError: Cannot cast array data from dtype('float64') to dtype('int64')
+ according to the rule 'safe'
+
+ A possible use of ``bincount`` is to perform sums over
+ variable-size chunks of an array, using the ``weights`` keyword.
+
+ >>> w = np.array([0.3, 0.5, 0.2, 0.7, 1., -0.6]) # weights
+ >>> x = np.array([0, 1, 1, 2, 2, 2])
+ >>> np.bincount(x, weights=w)
+ array([ 0.3, 0.7, 1.1])
+
+ """
+ return (x, weights)
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.ravel_multi_index)
+def ravel_multi_index(multi_index, dims, mode=None, order=None):
+ """
+ ravel_multi_index(multi_index, dims, mode='raise', order='C')
+
+ Converts a tuple of index arrays into an array of flat
+ indices, applying boundary modes to the multi-index.
+
+ Parameters
+ ----------
+ multi_index : tuple of array_like
+ A tuple of integer arrays, one array for each dimension.
+ dims : tuple of ints
+ The shape of array into which the indices from ``multi_index`` apply.
+ mode : {'raise', 'wrap', 'clip'}, optional
+ Specifies how out-of-bounds indices are handled. Can specify
+ either one mode or a tuple of modes, one mode per index.
+
+ * 'raise' -- raise an error (default)
+ * 'wrap' -- wrap around
+ * 'clip' -- clip to the range
+
+ In 'clip' mode, a negative index which would normally
+ wrap will clip to 0 instead.
+ order : {'C', 'F'}, optional
+ Determines whether the multi-index should be viewed as
+ indexing in row-major (C-style) or column-major
+ (Fortran-style) order.
+
+ Returns
+ -------
+ raveled_indices : ndarray
+ An array of indices into the flattened version of an array
+ of dimensions ``dims``.
+
+ See Also
+ --------
+ unravel_index
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> arr = np.array([[3,6,6],[4,5,1]])
+ >>> np.ravel_multi_index(arr, (7,6))
+ array([22, 41, 37])
+ >>> np.ravel_multi_index(arr, (7,6), order='F')
+ array([31, 41, 13])
+ >>> np.ravel_multi_index(arr, (4,6), mode='clip')
+ array([22, 23, 19])
+ >>> np.ravel_multi_index(arr, (4,4), mode=('clip','wrap'))
+ array([12, 13, 13])
+
+ >>> np.ravel_multi_index((3,1,4,1), (6,7,8,9))
+ 1621
+ """
+ return multi_index
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.unravel_index)
+def unravel_index(indices, shape=None, order=None):
+ """
+ unravel_index(indices, shape, order='C')
+
+ Converts a flat index or array of flat indices into a tuple
+ of coordinate arrays.
+
+ Parameters
+ ----------
+ indices : array_like
+ An integer array whose elements are indices into the flattened
+ version of an array of dimensions ``shape``. Before version 1.6.0,
+ this function accepted just one index value.
+ shape : tuple of ints
+ The shape of the array to use for unraveling ``indices``.
+ order : {'C', 'F'}, optional
+ Determines whether the indices should be viewed as indexing in
+ row-major (C-style) or column-major (Fortran-style) order.
+
+ Returns
+ -------
+ unraveled_coords : tuple of ndarray
+ Each array in the tuple has the same shape as the ``indices``
+ array.
+
+ See Also
+ --------
+ ravel_multi_index
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.unravel_index([22, 41, 37], (7,6))
+ (array([3, 6, 6]), array([4, 5, 1]))
+ >>> np.unravel_index([31, 41, 13], (7,6), order='F')
+ (array([3, 6, 6]), array([4, 5, 1]))
+
+ >>> np.unravel_index(1621, (6,7,8,9))
+ (3, 1, 4, 1)
+
+ """
+ return (indices,)
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.copyto)
+def copyto(dst, src, casting=None, where=None):
+ """
+ copyto(dst, src, casting='same_kind', where=True)
+
+ Copies values from one array to another, broadcasting as necessary.
+
+ Raises a TypeError if the `casting` rule is violated, and if
+ `where` is provided, it selects which elements to copy.
+
+ Parameters
+ ----------
+ dst : ndarray
+ The array into which values are copied.
+ src : array_like
+ The array from which values are copied.
+ casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
+ Controls what kind of data casting may occur when copying.
+
+ * 'no' means the data types should not be cast at all.
+ * 'equiv' means only byte-order changes are allowed.
+ * 'safe' means only casts which can preserve values are allowed.
+ * 'same_kind' means only safe casts or casts within a kind,
+ like float64 to float32, are allowed.
+ * 'unsafe' means any data conversions may be done.
+ where : array_like of bool, optional
+ A boolean array which is broadcasted to match the dimensions
+ of `dst`, and selects elements to copy from `src` to `dst`
+ wherever it contains the value True.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> A = np.array([4, 5, 6])
+ >>> B = [1, 2, 3]
+ >>> np.copyto(A, B)
+ >>> A
+ array([1, 2, 3])
+
+ >>> A = np.array([[1, 2, 3], [4, 5, 6]])
+ >>> B = [[4, 5, 6], [7, 8, 9]]
+ >>> np.copyto(A, B)
+ >>> A
+ array([[4, 5, 6],
+ [7, 8, 9]])
+
+ """
+ return (dst, src, where)
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.putmask)
+def putmask(a, /, mask, values):
+ """
+ putmask(a, mask, values)
+
+ Changes elements of an array based on conditional and input values.
+
+ Sets ``a.flat[n] = values[n]`` for each n where ``mask.flat[n]==True``.
+
+ If `values` is not the same size as `a` and `mask` then it will repeat.
+ This gives behavior different from ``a[mask] = values``.
+
+ Parameters
+ ----------
+ a : ndarray
+ Target array.
+ mask : array_like
+ Boolean mask array. It has to be the same shape as `a`.
+ values : array_like
+ Values to put into `a` where `mask` is True. If `values` is smaller
+ than `a` it will be repeated.
+
+ See Also
+ --------
+ place, put, take, copyto
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.arange(6).reshape(2, 3)
+ >>> np.putmask(x, x>2, x**2)
+ >>> x
+ array([[ 0, 1, 2],
+ [ 9, 16, 25]])
+
+ If `values` is smaller than `a` it is repeated:
+
+ >>> x = np.arange(5)
+ >>> np.putmask(x, x>1, [-33, -44])
+ >>> x
+ array([ 0, 1, -33, -44, -33])
+
+ """
+ return (a, mask, values)
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.packbits)
+def packbits(a, axis=None, bitorder='big'):
+ """
+ packbits(a, /, axis=None, bitorder='big')
+
+ Packs the elements of a binary-valued array into bits in a uint8 array.
+
+ The result is padded to full bytes by inserting zero bits at the end.
+
+ Parameters
+ ----------
+ a : array_like
+ An array of integers or booleans whose elements should be packed to
+ bits.
+ axis : int, optional
+ The dimension over which bit-packing is done.
+ ``None`` implies packing the flattened array.
+ bitorder : {'big', 'little'}, optional
+ The order of the input bits. 'big' will mimic bin(val),
+ ``[0, 0, 0, 0, 0, 0, 1, 1] => 3 = 0b00000011``, 'little' will
+ reverse the order so ``[1, 1, 0, 0, 0, 0, 0, 0] => 3``.
+ Defaults to 'big'.
+
+ Returns
+ -------
+ packed : ndarray
+ Array of type uint8 whose elements represent bits corresponding to the
+ logical (0 or nonzero) value of the input elements. The shape of
+ `packed` has the same number of dimensions as the input (unless `axis`
+ is None, in which case the output is 1-D).
+
+ See Also
+ --------
+ unpackbits: Unpacks elements of a uint8 array into a binary-valued output
+ array.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[[1,0,1],
+ ... [0,1,0]],
+ ... [[1,1,0],
+ ... [0,0,1]]])
+ >>> b = np.packbits(a, axis=-1)
+ >>> b
+ array([[[160],
+ [ 64]],
+ [[192],
+ [ 32]]], dtype=uint8)
+
+ Note that in binary 160 = 1010 0000, 64 = 0100 0000, 192 = 1100 0000,
+ and 32 = 0010 0000.
+
+ """
+ return (a,)
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.unpackbits)
+def unpackbits(a, axis=None, count=None, bitorder='big'):
+ """
+ unpackbits(a, /, axis=None, count=None, bitorder='big')
+
+ Unpacks elements of a uint8 array into a binary-valued output array.
+
+ Each element of `a` represents a bit-field that should be unpacked
+ into a binary-valued output array. The shape of the output array is
+ either 1-D (if `axis` is ``None``) or the same shape as the input
+ array with unpacking done along the axis specified.
+
+ Parameters
+ ----------
+ a : ndarray, uint8 type
+ Input array.
+ axis : int, optional
+ The dimension over which bit-unpacking is done.
+ ``None`` implies unpacking the flattened array.
+ count : int or None, optional
+ The number of elements to unpack along `axis`, provided as a way
+ of undoing the effect of packing a size that is not a multiple
+ of eight. A non-negative number means to only unpack `count`
+ bits. A negative number means to trim off that many bits from
+ the end. ``None`` means to unpack the entire array (the
+ default). Counts larger than the available number of bits will
+ add zero padding to the output. Negative counts must not
+ exceed the available number of bits.
+ bitorder : {'big', 'little'}, optional
+ The order of the returned bits. 'big' will mimic bin(val),
+ ``3 = 0b00000011 => [0, 0, 0, 0, 0, 0, 1, 1]``, 'little' will reverse
+ the order to ``[1, 1, 0, 0, 0, 0, 0, 0]``.
+ Defaults to 'big'.
+
+ Returns
+ -------
+ unpacked : ndarray, uint8 type
+ The elements are binary-valued (0 or 1).
+
+ See Also
+ --------
+ packbits : Packs the elements of a binary-valued array into bits in
+ a uint8 array.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[2], [7], [23]], dtype=np.uint8)
+ >>> a
+ array([[ 2],
+ [ 7],
+ [23]], dtype=uint8)
+ >>> b = np.unpackbits(a, axis=1)
+ >>> b
+ array([[0, 0, 0, 0, 0, 0, 1, 0],
+ [0, 0, 0, 0, 0, 1, 1, 1],
+ [0, 0, 0, 1, 0, 1, 1, 1]], dtype=uint8)
+ >>> c = np.unpackbits(a, axis=1, count=-3)
+ >>> c
+ array([[0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0]], dtype=uint8)
+
+ >>> p = np.packbits(b, axis=0)
+ >>> np.unpackbits(p, axis=0)
+ array([[0, 0, 0, 0, 0, 0, 1, 0],
+ [0, 0, 0, 0, 0, 1, 1, 1],
+ [0, 0, 0, 1, 0, 1, 1, 1],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8)
+ >>> np.array_equal(b, np.unpackbits(p, axis=0, count=b.shape[0]))
+ True
+
+ """
+ return (a,)
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.shares_memory)
+def shares_memory(a, b, max_work=None):
+ """
+ shares_memory(a, b, /, max_work=None)
+
+ Determine if two arrays share memory.
+
+ .. warning::
+
+ This function can be exponentially slow for some inputs, unless
+ `max_work` is set to zero or a positive integer.
+ If in doubt, use `numpy.may_share_memory` instead.
+
+ Parameters
+ ----------
+ a, b : ndarray
+ Input arrays
+ max_work : int, optional
+ Effort to spend on solving the overlap problem (maximum number
+ of candidate solutions to consider). The following special
+ values are recognized:
+
+ max_work=-1 (default)
+ The problem is solved exactly. In this case, the function returns
+ True only if there is an element shared between the arrays. Finding
+ the exact solution may take extremely long in some cases.
+ max_work=0
+ Only the memory bounds of a and b are checked.
+ This is equivalent to using ``may_share_memory()``.
+
+ Raises
+ ------
+ numpy.exceptions.TooHardError
+ Exceeded max_work.
+
+ Returns
+ -------
+ out : bool
+
+ See Also
+ --------
+ may_share_memory
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.array([1, 2, 3, 4])
+ >>> np.shares_memory(x, np.array([5, 6, 7]))
+ False
+ >>> np.shares_memory(x[::2], x)
+ True
+ >>> np.shares_memory(x[::2], x[1::2])
+ False
+
+ Checking whether two arrays share memory is NP-complete, and
+ runtime may increase exponentially in the number of
+ dimensions. Hence, `max_work` should generally be set to a finite
+ number, as it is possible to construct examples that take
+ extremely long to run:
+
+ >>> from numpy.lib.stride_tricks import as_strided
+ >>> x = np.zeros([192163377], dtype=np.int8)
+ >>> x1 = as_strided(
+ ... x, strides=(36674, 61119, 85569), shape=(1049, 1049, 1049))
+ >>> x2 = as_strided(
+ ... x[64023025:], strides=(12223, 12224, 1), shape=(1049, 1049, 1))
+ >>> np.shares_memory(x1, x2, max_work=1000)
+ Traceback (most recent call last):
+ ...
+ numpy.exceptions.TooHardError: Exceeded max_work
+
+ Running ``np.shares_memory(x1, x2)`` without `max_work` set takes
+ around 1 minute for this case. It is possible to find problems
+ that take still significantly longer.
+
+ """
+ return (a, b)
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.may_share_memory)
+def may_share_memory(a, b, max_work=None):
+ """
+ may_share_memory(a, b, /, max_work=None)
+
+ Determine if two arrays might share memory
+
+ A return of True does not necessarily mean that the two arrays
+ share any element. It just means that they *might*.
+
+ Only the memory bounds of a and b are checked by default.
+
+ Parameters
+ ----------
+ a, b : ndarray
+ Input arrays
+ max_work : int, optional
+ Effort to spend on solving the overlap problem. See
+ `shares_memory` for details. Default for ``may_share_memory``
+ is to do a bounds check.
+
+ Returns
+ -------
+ out : bool
+
+ See Also
+ --------
+ shares_memory
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.may_share_memory(np.array([1,2]), np.array([5,8,9]))
+ False
+ >>> x = np.zeros([3, 4])
+ >>> np.may_share_memory(x[:,0], x[:,1])
+ True
+
+ """
+ return (a, b)
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.is_busday)
+def is_busday(dates, weekmask=None, holidays=None, busdaycal=None, out=None):
+ """
+ is_busday(
+ dates,
+ weekmask='1111100',
+ holidays=None,
+ busdaycal=None,
+ out=None
+ )
+
+ Calculates which of the given dates are valid days, and which are not.
+
+ Parameters
+ ----------
+ dates : array_like of datetime64[D]
+ The array of dates to process.
+ weekmask : str or array_like of bool, optional
+ A seven-element array indicating which of Monday through Sunday are
+ valid days. May be specified as a length-seven list or array, like
+ [1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string
+ like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for
+ weekdays, optionally separated by white space. Valid abbreviations
+ are: Mon Tue Wed Thu Fri Sat Sun
+ holidays : array_like of datetime64[D], optional
+ An array of dates to consider as invalid dates. They may be
+ specified in any order, and NaT (not-a-time) dates are ignored.
+ This list is saved in a normalized form that is suited for
+ fast calculations of valid days.
+ busdaycal : busdaycalendar, optional
+ A `busdaycalendar` object which specifies the valid days. If this
+ parameter is provided, neither weekmask nor holidays may be
+ provided.
+ out : array of bool, optional
+ If provided, this array is filled with the result.
+
+ Returns
+ -------
+ out : array of bool
+ An array with the same shape as ``dates``, containing True for
+ each valid day, and False for each invalid day.
+
+ See Also
+ --------
+ busdaycalendar : An object that specifies a custom set of valid days.
+ busday_offset : Applies an offset counted in valid days.
+ busday_count : Counts how many valid days are in a half-open date range.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> # The weekdays are Friday, Saturday, and Monday
+ ... np.is_busday(['2011-07-01', '2011-07-02', '2011-07-18'],
+ ... holidays=['2011-07-01', '2011-07-04', '2011-07-17'])
+ array([False, False, True])
+ """
+ return (dates, weekmask, holidays, out)
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.busday_offset)
+def busday_offset(dates, offsets, roll=None, weekmask=None, holidays=None,
+ busdaycal=None, out=None):
+ """
+ busday_offset(
+ dates,
+ offsets,
+ roll='raise',
+ weekmask='1111100',
+ holidays=None,
+ busdaycal=None,
+ out=None
+ )
+
+ First adjusts the date to fall on a valid day according to
+ the ``roll`` rule, then applies offsets to the given dates
+ counted in valid days.
+
+ Parameters
+ ----------
+ dates : array_like of datetime64[D]
+ The array of dates to process.
+ offsets : array_like of int
+ The array of offsets, which is broadcast with ``dates``.
+ roll : {'raise', 'nat', 'forward', 'following', 'backward', 'preceding', \
+ 'modifiedfollowing', 'modifiedpreceding'}, optional
+ How to treat dates that do not fall on a valid day. The default
+ is 'raise'.
+
+ * 'raise' means to raise an exception for an invalid day.
+ * 'nat' means to return a NaT (not-a-time) for an invalid day.
+ * 'forward' and 'following' mean to take the first valid day
+ later in time.
+ * 'backward' and 'preceding' mean to take the first valid day
+ earlier in time.
+ * 'modifiedfollowing' means to take the first valid day
+ later in time unless it is across a Month boundary, in which
+ case to take the first valid day earlier in time.
+ * 'modifiedpreceding' means to take the first valid day
+ earlier in time unless it is across a Month boundary, in which
+ case to take the first valid day later in time.
+ weekmask : str or array_like of bool, optional
+ A seven-element array indicating which of Monday through Sunday are
+ valid days. May be specified as a length-seven list or array, like
+ [1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string
+ like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for
+ weekdays, optionally separated by white space. Valid abbreviations
+ are: Mon Tue Wed Thu Fri Sat Sun
+ holidays : array_like of datetime64[D], optional
+ An array of dates to consider as invalid dates. They may be
+ specified in any order, and NaT (not-a-time) dates are ignored.
+ This list is saved in a normalized form that is suited for
+ fast calculations of valid days.
+ busdaycal : busdaycalendar, optional
+ A `busdaycalendar` object which specifies the valid days. If this
+ parameter is provided, neither weekmask nor holidays may be
+ provided.
+ out : array of datetime64[D], optional
+ If provided, this array is filled with the result.
+
+ Returns
+ -------
+ out : array of datetime64[D]
+ An array with a shape from broadcasting ``dates`` and ``offsets``
+ together, containing the dates with offsets applied.
+
+ See Also
+ --------
+ busdaycalendar : An object that specifies a custom set of valid days.
+ is_busday : Returns a boolean array indicating valid days.
+ busday_count : Counts how many valid days are in a half-open date range.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> # First business day in October 2011 (not accounting for holidays)
+ ... np.busday_offset('2011-10', 0, roll='forward')
+ np.datetime64('2011-10-03')
+ >>> # Last business day in February 2012 (not accounting for holidays)
+ ... np.busday_offset('2012-03', -1, roll='forward')
+ np.datetime64('2012-02-29')
+ >>> # Third Wednesday in January 2011
+ ... np.busday_offset('2011-01', 2, roll='forward', weekmask='Wed')
+ np.datetime64('2011-01-19')
+ >>> # 2012 Mother's Day in Canada and the U.S.
+ ... np.busday_offset('2012-05', 1, roll='forward', weekmask='Sun')
+ np.datetime64('2012-05-13')
+
+ >>> # First business day on or after a date
+ ... np.busday_offset('2011-03-20', 0, roll='forward')
+ np.datetime64('2011-03-21')
+ >>> np.busday_offset('2011-03-22', 0, roll='forward')
+ np.datetime64('2011-03-22')
+ >>> # First business day after a date
+ ... np.busday_offset('2011-03-20', 1, roll='backward')
+ np.datetime64('2011-03-21')
+ >>> np.busday_offset('2011-03-22', 1, roll='backward')
+ np.datetime64('2011-03-23')
+ """
+ return (dates, offsets, weekmask, holidays, out)
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.busday_count)
+def busday_count(begindates, enddates, weekmask=None, holidays=None,
+ busdaycal=None, out=None):
+ """
+ busday_count(
+ begindates,
+ enddates,
+ weekmask='1111100',
+ holidays=[],
+ busdaycal=None,
+ out=None
+ )
+
+ Counts the number of valid days between `begindates` and
+ `enddates`, not including the day of `enddates`.
+
+ If ``enddates`` specifies a date value that is earlier than the
+ corresponding ``begindates`` date value, the count will be negative.
+
+ Parameters
+ ----------
+ begindates : array_like of datetime64[D]
+ The array of the first dates for counting.
+ enddates : array_like of datetime64[D]
+ The array of the end dates for counting, which are excluded
+ from the count themselves.
+ weekmask : str or array_like of bool, optional
+ A seven-element array indicating which of Monday through Sunday are
+ valid days. May be specified as a length-seven list or array, like
+ [1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string
+ like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for
+ weekdays, optionally separated by white space. Valid abbreviations
+ are: Mon Tue Wed Thu Fri Sat Sun
+ holidays : array_like of datetime64[D], optional
+ An array of dates to consider as invalid dates. They may be
+ specified in any order, and NaT (not-a-time) dates are ignored.
+ This list is saved in a normalized form that is suited for
+ fast calculations of valid days.
+ busdaycal : busdaycalendar, optional
+ A `busdaycalendar` object which specifies the valid days. If this
+ parameter is provided, neither weekmask nor holidays may be
+ provided.
+ out : array of int, optional
+ If provided, this array is filled with the result.
+
+ Returns
+ -------
+ out : array of int
+ An array with a shape from broadcasting ``begindates`` and ``enddates``
+ together, containing the number of valid days between
+ the begin and end dates.
+
+ See Also
+ --------
+ busdaycalendar : An object that specifies a custom set of valid days.
+ is_busday : Returns a boolean array indicating valid days.
+ busday_offset : Applies an offset counted in valid days.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> # Number of weekdays in January 2011
+ ... np.busday_count('2011-01', '2011-02')
+ 21
+ >>> # Number of weekdays in 2011
+ >>> np.busday_count('2011', '2012')
+ 260
+ >>> # Number of Saturdays in 2011
+ ... np.busday_count('2011', '2012', weekmask='Sat')
+ 53
+ """
+ return (begindates, enddates, weekmask, holidays, out)
+
+
+@array_function_from_c_func_and_dispatcher(
+ _multiarray_umath.datetime_as_string)
+def datetime_as_string(arr, unit=None, timezone=None, casting=None):
+ """
+ datetime_as_string(arr, unit=None, timezone='naive', casting='same_kind')
+
+ Convert an array of datetimes into an array of strings.
+
+ Parameters
+ ----------
+ arr : array_like of datetime64
+ The array of UTC timestamps to format.
+ unit : str
+ One of None, 'auto', or
+ a :ref:`datetime unit `.
+ timezone : {'naive', 'UTC', 'local'} or tzinfo
+ Timezone information to use when displaying the datetime. If 'UTC',
+ end with a Z to indicate UTC time. If 'local', convert to the local
+ timezone first, and suffix with a +-#### timezone offset. If a tzinfo
+ object, then do as with 'local', but use the specified timezone.
+ casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}
+ Casting to allow when changing between datetime units.
+
+ Returns
+ -------
+ str_arr : ndarray
+ An array of strings the same shape as `arr`.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> import pytz
+ >>> d = np.arange('2002-10-27T04:30', 4*60, 60, dtype='M8[m]')
+ >>> d
+ array(['2002-10-27T04:30', '2002-10-27T05:30', '2002-10-27T06:30',
+ '2002-10-27T07:30'], dtype='datetime64[m]')
+
+ Setting the timezone to UTC shows the same information, but with a Z suffix
+
+ >>> np.datetime_as_string(d, timezone='UTC')
+ array(['2002-10-27T04:30Z', '2002-10-27T05:30Z', '2002-10-27T06:30Z',
+ '2002-10-27T07:30Z'], dtype='>> np.datetime_as_string(d, timezone=pytz.timezone('US/Eastern'))
+ array(['2002-10-27T00:30-0400', '2002-10-27T01:30-0400',
+ '2002-10-27T01:30-0500', '2002-10-27T02:30-0500'], dtype='>> np.datetime_as_string(d, unit='h')
+ array(['2002-10-27T04', '2002-10-27T05', '2002-10-27T06', '2002-10-27T07'],
+ dtype='>> np.datetime_as_string(d, unit='s')
+ array(['2002-10-27T04:30:00', '2002-10-27T05:30:00', '2002-10-27T06:30:00',
+ '2002-10-27T07:30:00'], dtype='>> np.datetime_as_string(d, unit='h', casting='safe')
+ Traceback (most recent call last):
+ ...
+ TypeError: Cannot create a datetime string as units 'h' from a NumPy
+ datetime with units 'm' according to the rule 'safe'
+ """
+ return (arr,)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/multiarray.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/multiarray.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..ea304c0789aba1c4d44003c376e26847e6f06183
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/multiarray.pyi
@@ -0,0 +1,1355 @@
+# TODO: Sort out any and all missing functions in this namespace
+import datetime as dt
+from _typeshed import StrOrBytesPath, SupportsLenAndGetItem
+from collections.abc import Sequence, Callable, Iterable
+from typing import (
+ Literal as L,
+ Any,
+ TypeAlias,
+ overload,
+ TypeVar,
+ TypedDict,
+ SupportsIndex,
+ final,
+ Final,
+ Protocol,
+ ClassVar,
+ type_check_only,
+)
+from typing_extensions import CapsuleType, Unpack
+
+import numpy as np
+from numpy import ( # type: ignore[attr-defined]
+ # Re-exports
+ busdaycalendar,
+ broadcast,
+ correlate,
+ count_nonzero,
+ dtype,
+ einsum as c_einsum,
+ flatiter,
+ from_dlpack,
+ interp,
+ matmul,
+ ndarray,
+ nditer,
+ vecdot,
+
+ # The rest
+ ufunc,
+ str_,
+ uint8,
+ intp,
+ int_,
+ float64,
+ timedelta64,
+ datetime64,
+ generic,
+ unsignedinteger,
+ signedinteger,
+ floating,
+ complexfloating,
+ _AnyShapeType,
+ _OrderKACF,
+ _OrderCF,
+ _CastingKind,
+ _ModeKind,
+ _SupportsBuffer,
+ _SupportsFileMethods,
+ _CopyMode,
+ _NDIterFlagsKind,
+ _NDIterFlagsOp,
+)
+from numpy.lib._array_utils_impl import normalize_axis_index
+
+from numpy._typing import (
+ # Shapes
+ _ShapeLike,
+
+ # DTypes
+ DTypeLike,
+ _DTypeLike,
+ _SupportsDType,
+
+ # Arrays
+ NDArray,
+ ArrayLike,
+ _ArrayLike,
+ _SupportsArrayFunc,
+ _NestedSequence,
+ _ArrayLikeBool_co,
+ _ArrayLikeUInt_co,
+ _ArrayLikeInt_co,
+ _ArrayLikeFloat_co,
+ _ArrayLikeComplex_co,
+ _ArrayLikeTD64_co,
+ _ArrayLikeDT64_co,
+ _ArrayLikeObject_co,
+ _ArrayLikeStr_co,
+ _ArrayLikeBytes_co,
+ _ScalarLike_co,
+ _IntLike_co,
+ _FloatLike_co,
+ _TD64Like_co,
+)
+from numpy._typing._ufunc import (
+ _2PTuple,
+ _PyFunc_Nin1_Nout1,
+ _PyFunc_Nin2_Nout1,
+ _PyFunc_Nin3P_Nout1,
+ _PyFunc_Nin1P_Nout2P,
+)
+
+__all__ = [
+ "_ARRAY_API",
+ "ALLOW_THREADS",
+ "BUFSIZE",
+ "CLIP",
+ "DATETIMEUNITS",
+ "ITEM_HASOBJECT",
+ "ITEM_IS_POINTER",
+ "LIST_PICKLE",
+ "MAXDIMS",
+ "MAY_SHARE_BOUNDS",
+ "MAY_SHARE_EXACT",
+ "NEEDS_INIT",
+ "NEEDS_PYAPI",
+ "RAISE",
+ "USE_GETITEM",
+ "USE_SETITEM",
+ "WRAP",
+ "_flagdict",
+ "from_dlpack",
+ "_place",
+ "_reconstruct",
+ "_vec_string",
+ "_monotonicity",
+ "add_docstring",
+ "arange",
+ "array",
+ "asarray",
+ "asanyarray",
+ "ascontiguousarray",
+ "asfortranarray",
+ "bincount",
+ "broadcast",
+ "busday_count",
+ "busday_offset",
+ "busdaycalendar",
+ "can_cast",
+ "compare_chararrays",
+ "concatenate",
+ "copyto",
+ "correlate",
+ "correlate2",
+ "count_nonzero",
+ "c_einsum",
+ "datetime_as_string",
+ "datetime_data",
+ "dot",
+ "dragon4_positional",
+ "dragon4_scientific",
+ "dtype",
+ "empty",
+ "empty_like",
+ "error",
+ "flagsobj",
+ "flatiter",
+ "format_longfloat",
+ "frombuffer",
+ "fromfile",
+ "fromiter",
+ "fromstring",
+ "get_handler_name",
+ "get_handler_version",
+ "inner",
+ "interp",
+ "interp_complex",
+ "is_busday",
+ "lexsort",
+ "matmul",
+ "vecdot",
+ "may_share_memory",
+ "min_scalar_type",
+ "ndarray",
+ "nditer",
+ "nested_iters",
+ "normalize_axis_index",
+ "packbits",
+ "promote_types",
+ "putmask",
+ "ravel_multi_index",
+ "result_type",
+ "scalar",
+ "set_datetimeparse_function",
+ "set_typeDict",
+ "shares_memory",
+ "typeinfo",
+ "unpackbits",
+ "unravel_index",
+ "vdot",
+ "where",
+ "zeros",
+]
+
+_SCT = TypeVar("_SCT", bound=generic)
+_DType = TypeVar("_DType", bound=np.dtype[Any])
+_ArrayType = TypeVar("_ArrayType", bound=ndarray[Any, Any])
+_ArrayType_co = TypeVar(
+ "_ArrayType_co",
+ bound=ndarray[Any, Any],
+ covariant=True,
+)
+_ReturnType = TypeVar("_ReturnType")
+_IDType = TypeVar("_IDType")
+_Nin = TypeVar("_Nin", bound=int)
+_Nout = TypeVar("_Nout", bound=int)
+
+_ShapeT = TypeVar("_ShapeT", bound=tuple[int, ...])
+_Array: TypeAlias = ndarray[_ShapeT, dtype[_SCT]]
+_Array1D: TypeAlias = ndarray[tuple[int], dtype[_SCT]]
+
+# Valid time units
+_UnitKind: TypeAlias = L[
+ "Y",
+ "M",
+ "D",
+ "h",
+ "m",
+ "s",
+ "ms",
+ "us", "μs",
+ "ns",
+ "ps",
+ "fs",
+ "as",
+]
+_RollKind: TypeAlias = L[ # `raise` is deliberately excluded
+ "nat",
+ "forward",
+ "following",
+ "backward",
+ "preceding",
+ "modifiedfollowing",
+ "modifiedpreceding",
+]
+
+@type_check_only
+class _SupportsArray(Protocol[_ArrayType_co]):
+ def __array__(self, /) -> _ArrayType_co: ...
+
+@type_check_only
+class _KwargsEmpty(TypedDict, total=False):
+ device: None | L["cpu"]
+ like: None | _SupportsArrayFunc
+
+@type_check_only
+class _ConstructorEmpty(Protocol):
+ # 1-D shape
+ @overload
+ def __call__(
+ self,
+ /,
+ shape: SupportsIndex,
+ dtype: None = ...,
+ order: _OrderCF = ...,
+ **kwargs: Unpack[_KwargsEmpty],
+ ) -> _Array1D[float64]: ...
+ @overload
+ def __call__(
+ self,
+ /,
+ shape: SupportsIndex,
+ dtype: _DType | _SupportsDType[_DType],
+ order: _OrderCF = ...,
+ **kwargs: Unpack[_KwargsEmpty],
+ ) -> ndarray[tuple[int], _DType]: ...
+ @overload
+ def __call__(
+ self,
+ /,
+ shape: SupportsIndex,
+ dtype: type[_SCT],
+ order: _OrderCF = ...,
+ **kwargs: Unpack[_KwargsEmpty],
+ ) -> _Array1D[_SCT]: ...
+ @overload
+ def __call__(
+ self,
+ /,
+ shape: SupportsIndex,
+ dtype: DTypeLike,
+ order: _OrderCF = ...,
+ **kwargs: Unpack[_KwargsEmpty],
+ ) -> _Array1D[Any]: ...
+
+ # known shape
+ @overload
+ def __call__(
+ self,
+ /,
+ shape: _AnyShapeType,
+ dtype: None = ...,
+ order: _OrderCF = ...,
+ **kwargs: Unpack[_KwargsEmpty],
+ ) -> _Array[_AnyShapeType, float64]: ...
+ @overload
+ def __call__(
+ self,
+ /,
+ shape: _AnyShapeType,
+ dtype: _DType | _SupportsDType[_DType],
+ order: _OrderCF = ...,
+ **kwargs: Unpack[_KwargsEmpty],
+ ) -> ndarray[_AnyShapeType, _DType]: ...
+ @overload
+ def __call__(
+ self,
+ /,
+ shape: _AnyShapeType,
+ dtype: type[_SCT],
+ order: _OrderCF = ...,
+ **kwargs: Unpack[_KwargsEmpty],
+ ) -> _Array[_AnyShapeType, _SCT]: ...
+ @overload
+ def __call__(
+ self,
+ /,
+ shape: _AnyShapeType,
+ dtype: DTypeLike,
+ order: _OrderCF = ...,
+ **kwargs: Unpack[_KwargsEmpty],
+ ) -> _Array[_AnyShapeType, Any]: ...
+
+ # unknown shape
+ @overload
+ def __call__(
+ self, /,
+ shape: _ShapeLike,
+ dtype: None = ...,
+ order: _OrderCF = ...,
+ **kwargs: Unpack[_KwargsEmpty],
+ ) -> NDArray[float64]: ...
+ @overload
+ def __call__(
+ self, /,
+ shape: _ShapeLike,
+ dtype: _DType | _SupportsDType[_DType],
+ order: _OrderCF = ...,
+ **kwargs: Unpack[_KwargsEmpty],
+ ) -> ndarray[Any, _DType]: ...
+ @overload
+ def __call__(
+ self, /,
+ shape: _ShapeLike,
+ dtype: type[_SCT],
+ order: _OrderCF = ...,
+ **kwargs: Unpack[_KwargsEmpty],
+ ) -> NDArray[_SCT]: ...
+ @overload
+ def __call__(
+ self, /,
+ shape: _ShapeLike,
+ dtype: DTypeLike,
+ order: _OrderCF = ...,
+ **kwargs: Unpack[_KwargsEmpty],
+ ) -> NDArray[Any]: ...
+
+# using `Final` or `TypeAlias` will break stubtest
+error = Exception
+
+# from ._multiarray_umath
+ITEM_HASOBJECT: Final[L[1]]
+LIST_PICKLE: Final[L[2]]
+ITEM_IS_POINTER: Final[L[4]]
+NEEDS_INIT: Final[L[8]]
+NEEDS_PYAPI: Final[L[16]]
+USE_GETITEM: Final[L[32]]
+USE_SETITEM: Final[L[64]]
+DATETIMEUNITS: Final[CapsuleType]
+_ARRAY_API: Final[CapsuleType]
+_flagdict: Final[dict[str, int]]
+_monotonicity: Final[Callable[..., object]]
+_place: Final[Callable[..., object]]
+_reconstruct: Final[Callable[..., object]]
+_vec_string: Final[Callable[..., object]]
+correlate2: Final[Callable[..., object]]
+dragon4_positional: Final[Callable[..., object]]
+dragon4_scientific: Final[Callable[..., object]]
+interp_complex: Final[Callable[..., object]]
+set_datetimeparse_function: Final[Callable[..., object]]
+def get_handler_name(a: NDArray[Any] = ..., /) -> str | None: ...
+def get_handler_version(a: NDArray[Any] = ..., /) -> int | None: ...
+def format_longfloat(x: np.longdouble, precision: int) -> str: ...
+def scalar(dtype: _DType, object: bytes | object = ...) -> ndarray[tuple[()], _DType]: ...
+def set_typeDict(dict_: dict[str, np.dtype[Any]], /) -> None: ...
+typeinfo: Final[dict[str, np.dtype[np.generic]]]
+
+ALLOW_THREADS: Final[int] # 0 or 1 (system-specific)
+BUFSIZE: L[8192]
+CLIP: L[0]
+WRAP: L[1]
+RAISE: L[2]
+MAXDIMS: L[32]
+MAY_SHARE_BOUNDS: L[0]
+MAY_SHARE_EXACT: L[-1]
+tracemalloc_domain: L[389047]
+
+zeros: Final[_ConstructorEmpty]
+empty: Final[_ConstructorEmpty]
+
+@overload
+def empty_like(
+ prototype: _ArrayType,
+ dtype: None = ...,
+ order: _OrderKACF = ...,
+ subok: bool = ...,
+ shape: None | _ShapeLike = ...,
+ *,
+ device: None | L["cpu"] = ...,
+) -> _ArrayType: ...
+@overload
+def empty_like(
+ prototype: _ArrayLike[_SCT],
+ dtype: None = ...,
+ order: _OrderKACF = ...,
+ subok: bool = ...,
+ shape: None | _ShapeLike = ...,
+ *,
+ device: None | L["cpu"] = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def empty_like(
+ prototype: object,
+ dtype: None = ...,
+ order: _OrderKACF = ...,
+ subok: bool = ...,
+ shape: None | _ShapeLike = ...,
+ *,
+ device: None | L["cpu"] = ...,
+) -> NDArray[Any]: ...
+@overload
+def empty_like(
+ prototype: Any,
+ dtype: _DTypeLike[_SCT],
+ order: _OrderKACF = ...,
+ subok: bool = ...,
+ shape: None | _ShapeLike = ...,
+ *,
+ device: None | L["cpu"] = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def empty_like(
+ prototype: Any,
+ dtype: DTypeLike,
+ order: _OrderKACF = ...,
+ subok: bool = ...,
+ shape: None | _ShapeLike = ...,
+ *,
+ device: None | L["cpu"] = ...,
+) -> NDArray[Any]: ...
+
+@overload
+def array(
+ object: _ArrayType,
+ dtype: None = ...,
+ *,
+ copy: None | bool | _CopyMode = ...,
+ order: _OrderKACF = ...,
+ subok: L[True],
+ ndmin: int = ...,
+ like: None | _SupportsArrayFunc = ...,
+) -> _ArrayType: ...
+@overload
+def array(
+ object: _SupportsArray[_ArrayType],
+ dtype: None = ...,
+ *,
+ copy: None | bool | _CopyMode = ...,
+ order: _OrderKACF = ...,
+ subok: L[True],
+ ndmin: L[0] = ...,
+ like: None | _SupportsArrayFunc = ...,
+) -> _ArrayType: ...
+@overload
+def array(
+ object: _ArrayLike[_SCT],
+ dtype: None = ...,
+ *,
+ copy: None | bool | _CopyMode = ...,
+ order: _OrderKACF = ...,
+ subok: bool = ...,
+ ndmin: int = ...,
+ like: None | _SupportsArrayFunc = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def array(
+ object: object,
+ dtype: None = ...,
+ *,
+ copy: None | bool | _CopyMode = ...,
+ order: _OrderKACF = ...,
+ subok: bool = ...,
+ ndmin: int = ...,
+ like: None | _SupportsArrayFunc = ...,
+) -> NDArray[Any]: ...
+@overload
+def array(
+ object: Any,
+ dtype: _DTypeLike[_SCT],
+ *,
+ copy: None | bool | _CopyMode = ...,
+ order: _OrderKACF = ...,
+ subok: bool = ...,
+ ndmin: int = ...,
+ like: None | _SupportsArrayFunc = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def array(
+ object: Any,
+ dtype: DTypeLike,
+ *,
+ copy: None | bool | _CopyMode = ...,
+ order: _OrderKACF = ...,
+ subok: bool = ...,
+ ndmin: int = ...,
+ like: None | _SupportsArrayFunc = ...,
+) -> NDArray[Any]: ...
+
+@overload
+def unravel_index( # type: ignore[misc]
+ indices: _IntLike_co,
+ shape: _ShapeLike,
+ order: _OrderCF = ...,
+) -> tuple[intp, ...]: ...
+@overload
+def unravel_index(
+ indices: _ArrayLikeInt_co,
+ shape: _ShapeLike,
+ order: _OrderCF = ...,
+) -> tuple[NDArray[intp], ...]: ...
+
+@overload
+def ravel_multi_index( # type: ignore[misc]
+ multi_index: Sequence[_IntLike_co],
+ dims: Sequence[SupportsIndex],
+ mode: _ModeKind | tuple[_ModeKind, ...] = ...,
+ order: _OrderCF = ...,
+) -> intp: ...
+@overload
+def ravel_multi_index(
+ multi_index: Sequence[_ArrayLikeInt_co],
+ dims: Sequence[SupportsIndex],
+ mode: _ModeKind | tuple[_ModeKind, ...] = ...,
+ order: _OrderCF = ...,
+) -> NDArray[intp]: ...
+
+# NOTE: Allow any sequence of array-like objects
+@overload
+def concatenate( # type: ignore[misc]
+ arrays: _ArrayLike[_SCT],
+ /,
+ axis: None | SupportsIndex = ...,
+ out: None = ...,
+ *,
+ dtype: None = ...,
+ casting: None | _CastingKind = ...
+) -> NDArray[_SCT]: ...
+@overload
+def concatenate( # type: ignore[misc]
+ arrays: SupportsLenAndGetItem[ArrayLike],
+ /,
+ axis: None | SupportsIndex = ...,
+ out: None = ...,
+ *,
+ dtype: None = ...,
+ casting: None | _CastingKind = ...
+) -> NDArray[Any]: ...
+@overload
+def concatenate( # type: ignore[misc]
+ arrays: SupportsLenAndGetItem[ArrayLike],
+ /,
+ axis: None | SupportsIndex = ...,
+ out: None = ...,
+ *,
+ dtype: _DTypeLike[_SCT],
+ casting: None | _CastingKind = ...
+) -> NDArray[_SCT]: ...
+@overload
+def concatenate( # type: ignore[misc]
+ arrays: SupportsLenAndGetItem[ArrayLike],
+ /,
+ axis: None | SupportsIndex = ...,
+ out: None = ...,
+ *,
+ dtype: DTypeLike,
+ casting: None | _CastingKind = ...
+) -> NDArray[Any]: ...
+@overload
+def concatenate(
+ arrays: SupportsLenAndGetItem[ArrayLike],
+ /,
+ axis: None | SupportsIndex = ...,
+ out: _ArrayType = ...,
+ *,
+ dtype: DTypeLike = ...,
+ casting: None | _CastingKind = ...
+) -> _ArrayType: ...
+
+def inner(
+ a: ArrayLike,
+ b: ArrayLike,
+ /,
+) -> Any: ...
+
+@overload
+def where(
+ condition: ArrayLike,
+ /,
+) -> tuple[NDArray[intp], ...]: ...
+@overload
+def where(
+ condition: ArrayLike,
+ x: ArrayLike,
+ y: ArrayLike,
+ /,
+) -> NDArray[Any]: ...
+
+def lexsort(
+ keys: ArrayLike,
+ axis: None | SupportsIndex = ...,
+) -> Any: ...
+
+def can_cast(
+ from_: ArrayLike | DTypeLike,
+ to: DTypeLike,
+ casting: None | _CastingKind = ...,
+) -> bool: ...
+
+def min_scalar_type(
+ a: ArrayLike, /,
+) -> dtype[Any]: ...
+
+def result_type(
+ *arrays_and_dtypes: ArrayLike | DTypeLike,
+) -> dtype[Any]: ...
+
+@overload
+def dot(a: ArrayLike, b: ArrayLike, out: None = ...) -> Any: ...
+@overload
+def dot(a: ArrayLike, b: ArrayLike, out: _ArrayType) -> _ArrayType: ...
+
+@overload
+def vdot(a: _ArrayLikeBool_co, b: _ArrayLikeBool_co, /) -> np.bool: ... # type: ignore[misc]
+@overload
+def vdot(a: _ArrayLikeUInt_co, b: _ArrayLikeUInt_co, /) -> unsignedinteger[Any]: ... # type: ignore[misc]
+@overload
+def vdot(a: _ArrayLikeInt_co, b: _ArrayLikeInt_co, /) -> signedinteger[Any]: ... # type: ignore[misc]
+@overload
+def vdot(a: _ArrayLikeFloat_co, b: _ArrayLikeFloat_co, /) -> floating[Any]: ... # type: ignore[misc]
+@overload
+def vdot(a: _ArrayLikeComplex_co, b: _ArrayLikeComplex_co, /) -> complexfloating[Any, Any]: ... # type: ignore[misc]
+@overload
+def vdot(a: _ArrayLikeTD64_co, b: _ArrayLikeTD64_co, /) -> timedelta64: ...
+@overload
+def vdot(a: _ArrayLikeObject_co, b: Any, /) -> Any: ...
+@overload
+def vdot(a: Any, b: _ArrayLikeObject_co, /) -> Any: ...
+
+def bincount(
+ x: ArrayLike,
+ /,
+ weights: None | ArrayLike = ...,
+ minlength: SupportsIndex = ...,
+) -> NDArray[intp]: ...
+
+def copyto(
+ dst: NDArray[Any],
+ src: ArrayLike,
+ casting: None | _CastingKind = ...,
+ where: None | _ArrayLikeBool_co = ...,
+) -> None: ...
+
+def putmask(
+ a: NDArray[Any],
+ /,
+ mask: _ArrayLikeBool_co,
+ values: ArrayLike,
+) -> None: ...
+
+def packbits(
+ a: _ArrayLikeInt_co,
+ /,
+ axis: None | SupportsIndex = ...,
+ bitorder: L["big", "little"] = ...,
+) -> NDArray[uint8]: ...
+
+def unpackbits(
+ a: _ArrayLike[uint8],
+ /,
+ axis: None | SupportsIndex = ...,
+ count: None | SupportsIndex = ...,
+ bitorder: L["big", "little"] = ...,
+) -> NDArray[uint8]: ...
+
+def shares_memory(
+ a: object,
+ b: object,
+ /,
+ max_work: None | int = ...,
+) -> bool: ...
+
+def may_share_memory(
+ a: object,
+ b: object,
+ /,
+ max_work: None | int = ...,
+) -> bool: ...
+
+@overload
+def asarray(
+ a: _ArrayLike[_SCT],
+ dtype: None = ...,
+ order: _OrderKACF = ...,
+ *,
+ device: None | L["cpu"] = ...,
+ copy: None | bool = ...,
+ like: None | _SupportsArrayFunc = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def asarray(
+ a: object,
+ dtype: None = ...,
+ order: _OrderKACF = ...,
+ *,
+ device: None | L["cpu"] = ...,
+ copy: None | bool = ...,
+ like: None | _SupportsArrayFunc = ...,
+) -> NDArray[Any]: ...
+@overload
+def asarray(
+ a: Any,
+ dtype: _DTypeLike[_SCT],
+ order: _OrderKACF = ...,
+ *,
+ device: None | L["cpu"] = ...,
+ copy: None | bool = ...,
+ like: None | _SupportsArrayFunc = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def asarray(
+ a: Any,
+ dtype: DTypeLike,
+ order: _OrderKACF = ...,
+ *,
+ device: None | L["cpu"] = ...,
+ copy: None | bool = ...,
+ like: None | _SupportsArrayFunc = ...,
+) -> NDArray[Any]: ...
+
+@overload
+def asanyarray(
+ a: _ArrayType, # Preserve subclass-information
+ dtype: None = ...,
+ order: _OrderKACF = ...,
+ *,
+ device: None | L["cpu"] = ...,
+ copy: None | bool = ...,
+ like: None | _SupportsArrayFunc = ...,
+) -> _ArrayType: ...
+@overload
+def asanyarray(
+ a: _ArrayLike[_SCT],
+ dtype: None = ...,
+ order: _OrderKACF = ...,
+ *,
+ device: None | L["cpu"] = ...,
+ copy: None | bool = ...,
+ like: None | _SupportsArrayFunc = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def asanyarray(
+ a: object,
+ dtype: None = ...,
+ order: _OrderKACF = ...,
+ *,
+ device: None | L["cpu"] = ...,
+ copy: None | bool = ...,
+ like: None | _SupportsArrayFunc = ...,
+) -> NDArray[Any]: ...
+@overload
+def asanyarray(
+ a: Any,
+ dtype: _DTypeLike[_SCT],
+ order: _OrderKACF = ...,
+ *,
+ device: None | L["cpu"] = ...,
+ copy: None | bool = ...,
+ like: None | _SupportsArrayFunc = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def asanyarray(
+ a: Any,
+ dtype: DTypeLike,
+ order: _OrderKACF = ...,
+ *,
+ device: None | L["cpu"] = ...,
+ copy: None | bool = ...,
+ like: None | _SupportsArrayFunc = ...,
+) -> NDArray[Any]: ...
+
+@overload
+def ascontiguousarray(
+ a: _ArrayLike[_SCT],
+ dtype: None = ...,
+ *,
+ like: None | _SupportsArrayFunc = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def ascontiguousarray(
+ a: object,
+ dtype: None = ...,
+ *,
+ like: None | _SupportsArrayFunc = ...,
+) -> NDArray[Any]: ...
+@overload
+def ascontiguousarray(
+ a: Any,
+ dtype: _DTypeLike[_SCT],
+ *,
+ like: None | _SupportsArrayFunc = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def ascontiguousarray(
+ a: Any,
+ dtype: DTypeLike,
+ *,
+ like: None | _SupportsArrayFunc = ...,
+) -> NDArray[Any]: ...
+
+@overload
+def asfortranarray(
+ a: _ArrayLike[_SCT],
+ dtype: None = ...,
+ *,
+ like: None | _SupportsArrayFunc = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def asfortranarray(
+ a: object,
+ dtype: None = ...,
+ *,
+ like: None | _SupportsArrayFunc = ...,
+) -> NDArray[Any]: ...
+@overload
+def asfortranarray(
+ a: Any,
+ dtype: _DTypeLike[_SCT],
+ *,
+ like: None | _SupportsArrayFunc = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def asfortranarray(
+ a: Any,
+ dtype: DTypeLike,
+ *,
+ like: None | _SupportsArrayFunc = ...,
+) -> NDArray[Any]: ...
+
+def promote_types(__type1: DTypeLike, __type2: DTypeLike) -> dtype[Any]: ...
+
+# `sep` is a de facto mandatory argument, as its default value is deprecated
+@overload
+def fromstring(
+ string: str | bytes,
+ dtype: None = ...,
+ count: SupportsIndex = ...,
+ *,
+ sep: str,
+ like: None | _SupportsArrayFunc = ...,
+) -> NDArray[float64]: ...
+@overload
+def fromstring(
+ string: str | bytes,
+ dtype: _DTypeLike[_SCT],
+ count: SupportsIndex = ...,
+ *,
+ sep: str,
+ like: None | _SupportsArrayFunc = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def fromstring(
+ string: str | bytes,
+ dtype: DTypeLike,
+ count: SupportsIndex = ...,
+ *,
+ sep: str,
+ like: None | _SupportsArrayFunc = ...,
+) -> NDArray[Any]: ...
+
+@overload
+def frompyfunc( # type: ignore[overload-overlap]
+ func: Callable[[Any], _ReturnType], /,
+ nin: L[1],
+ nout: L[1],
+ *,
+ identity: None = ...,
+) -> _PyFunc_Nin1_Nout1[_ReturnType, None]: ...
+@overload
+def frompyfunc( # type: ignore[overload-overlap]
+ func: Callable[[Any], _ReturnType], /,
+ nin: L[1],
+ nout: L[1],
+ *,
+ identity: _IDType,
+) -> _PyFunc_Nin1_Nout1[_ReturnType, _IDType]: ...
+@overload
+def frompyfunc( # type: ignore[overload-overlap]
+ func: Callable[[Any, Any], _ReturnType], /,
+ nin: L[2],
+ nout: L[1],
+ *,
+ identity: None = ...,
+) -> _PyFunc_Nin2_Nout1[_ReturnType, None]: ...
+@overload
+def frompyfunc( # type: ignore[overload-overlap]
+ func: Callable[[Any, Any], _ReturnType], /,
+ nin: L[2],
+ nout: L[1],
+ *,
+ identity: _IDType,
+) -> _PyFunc_Nin2_Nout1[_ReturnType, _IDType]: ...
+@overload
+def frompyfunc( # type: ignore[overload-overlap]
+ func: Callable[..., _ReturnType], /,
+ nin: _Nin,
+ nout: L[1],
+ *,
+ identity: None = ...,
+) -> _PyFunc_Nin3P_Nout1[_ReturnType, None, _Nin]: ...
+@overload
+def frompyfunc( # type: ignore[overload-overlap]
+ func: Callable[..., _ReturnType], /,
+ nin: _Nin,
+ nout: L[1],
+ *,
+ identity: _IDType,
+) -> _PyFunc_Nin3P_Nout1[_ReturnType, _IDType, _Nin]: ...
+@overload
+def frompyfunc(
+ func: Callable[..., _2PTuple[_ReturnType]], /,
+ nin: _Nin,
+ nout: _Nout,
+ *,
+ identity: None = ...,
+) -> _PyFunc_Nin1P_Nout2P[_ReturnType, None, _Nin, _Nout]: ...
+@overload
+def frompyfunc(
+ func: Callable[..., _2PTuple[_ReturnType]], /,
+ nin: _Nin,
+ nout: _Nout,
+ *,
+ identity: _IDType,
+) -> _PyFunc_Nin1P_Nout2P[_ReturnType, _IDType, _Nin, _Nout]: ...
+@overload
+def frompyfunc(
+ func: Callable[..., Any], /,
+ nin: SupportsIndex,
+ nout: SupportsIndex,
+ *,
+ identity: None | object = ...,
+) -> ufunc: ...
+
+@overload
+def fromfile(
+ file: StrOrBytesPath | _SupportsFileMethods,
+ dtype: None = ...,
+ count: SupportsIndex = ...,
+ sep: str = ...,
+ offset: SupportsIndex = ...,
+ *,
+ like: None | _SupportsArrayFunc = ...,
+) -> NDArray[float64]: ...
+@overload
+def fromfile(
+ file: StrOrBytesPath | _SupportsFileMethods,
+ dtype: _DTypeLike[_SCT],
+ count: SupportsIndex = ...,
+ sep: str = ...,
+ offset: SupportsIndex = ...,
+ *,
+ like: None | _SupportsArrayFunc = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def fromfile(
+ file: StrOrBytesPath | _SupportsFileMethods,
+ dtype: DTypeLike,
+ count: SupportsIndex = ...,
+ sep: str = ...,
+ offset: SupportsIndex = ...,
+ *,
+ like: None | _SupportsArrayFunc = ...,
+) -> NDArray[Any]: ...
+
+@overload
+def fromiter(
+ iter: Iterable[Any],
+ dtype: _DTypeLike[_SCT],
+ count: SupportsIndex = ...,
+ *,
+ like: None | _SupportsArrayFunc = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def fromiter(
+ iter: Iterable[Any],
+ dtype: DTypeLike,
+ count: SupportsIndex = ...,
+ *,
+ like: None | _SupportsArrayFunc = ...,
+) -> NDArray[Any]: ...
+
+@overload
+def frombuffer(
+ buffer: _SupportsBuffer,
+ dtype: None = ...,
+ count: SupportsIndex = ...,
+ offset: SupportsIndex = ...,
+ *,
+ like: None | _SupportsArrayFunc = ...,
+) -> NDArray[float64]: ...
+@overload
+def frombuffer(
+ buffer: _SupportsBuffer,
+ dtype: _DTypeLike[_SCT],
+ count: SupportsIndex = ...,
+ offset: SupportsIndex = ...,
+ *,
+ like: None | _SupportsArrayFunc = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def frombuffer(
+ buffer: _SupportsBuffer,
+ dtype: DTypeLike,
+ count: SupportsIndex = ...,
+ offset: SupportsIndex = ...,
+ *,
+ like: None | _SupportsArrayFunc = ...,
+) -> NDArray[Any]: ...
+
+@overload
+def arange( # type: ignore[misc]
+ stop: _IntLike_co,
+ /, *,
+ dtype: None = ...,
+ device: None | L["cpu"] = ...,
+ like: None | _SupportsArrayFunc = ...,
+) -> _Array1D[signedinteger]: ...
+@overload
+def arange( # type: ignore[misc]
+ start: _IntLike_co,
+ stop: _IntLike_co,
+ step: _IntLike_co = ...,
+ dtype: None = ...,
+ *,
+ device: None | L["cpu"] = ...,
+ like: None | _SupportsArrayFunc = ...,
+) -> _Array1D[signedinteger]: ...
+@overload
+def arange( # type: ignore[misc]
+ stop: _FloatLike_co,
+ /, *,
+ dtype: None = ...,
+ device: None | L["cpu"] = ...,
+ like: None | _SupportsArrayFunc = ...,
+) -> _Array1D[floating]: ...
+@overload
+def arange( # type: ignore[misc]
+ start: _FloatLike_co,
+ stop: _FloatLike_co,
+ step: _FloatLike_co = ...,
+ dtype: None = ...,
+ *,
+ device: None | L["cpu"] = ...,
+ like: None | _SupportsArrayFunc = ...,
+) -> _Array1D[floating]: ...
+@overload
+def arange(
+ stop: _TD64Like_co,
+ /, *,
+ dtype: None = ...,
+ device: None | L["cpu"] = ...,
+ like: None | _SupportsArrayFunc = ...,
+) -> _Array1D[timedelta64]: ...
+@overload
+def arange(
+ start: _TD64Like_co,
+ stop: _TD64Like_co,
+ step: _TD64Like_co = ...,
+ dtype: None = ...,
+ *,
+ device: None | L["cpu"] = ...,
+ like: None | _SupportsArrayFunc = ...,
+) -> _Array1D[timedelta64]: ...
+@overload
+def arange( # both start and stop must always be specified for datetime64
+ start: datetime64,
+ stop: datetime64,
+ step: datetime64 = ...,
+ dtype: None = ...,
+ *,
+ device: None | L["cpu"] = ...,
+ like: None | _SupportsArrayFunc = ...,
+) -> _Array1D[datetime64]: ...
+@overload
+def arange(
+ stop: Any,
+ /, *,
+ dtype: _DTypeLike[_SCT],
+ device: None | L["cpu"] = ...,
+ like: None | _SupportsArrayFunc = ...,
+) -> _Array1D[_SCT]: ...
+@overload
+def arange(
+ start: Any,
+ stop: Any,
+ step: Any = ...,
+ dtype: _DTypeLike[_SCT] = ...,
+ *,
+ device: None | L["cpu"] = ...,
+ like: None | _SupportsArrayFunc = ...,
+) -> _Array1D[_SCT]: ...
+@overload
+def arange(
+ stop: Any, /,
+ *,
+ dtype: DTypeLike,
+ device: None | L["cpu"] = ...,
+ like: None | _SupportsArrayFunc = ...,
+) -> _Array1D[Any]: ...
+@overload
+def arange(
+ start: Any,
+ stop: Any,
+ step: Any = ...,
+ dtype: DTypeLike = ...,
+ *,
+ device: None | L["cpu"] = ...,
+ like: None | _SupportsArrayFunc = ...,
+) -> _Array1D[Any]: ...
+
+def datetime_data(
+ dtype: str | _DTypeLike[datetime64] | _DTypeLike[timedelta64], /,
+) -> tuple[str, int]: ...
+
+# The datetime functions perform unsafe casts to `datetime64[D]`,
+# so a lot of different argument types are allowed here
+
+@overload
+def busday_count( # type: ignore[misc]
+ begindates: _ScalarLike_co | dt.date,
+ enddates: _ScalarLike_co | dt.date,
+ weekmask: ArrayLike = ...,
+ holidays: None | ArrayLike | dt.date | _NestedSequence[dt.date] = ...,
+ busdaycal: None | busdaycalendar = ...,
+ out: None = ...,
+) -> int_: ...
+@overload
+def busday_count( # type: ignore[misc]
+ begindates: ArrayLike | dt.date | _NestedSequence[dt.date],
+ enddates: ArrayLike | dt.date | _NestedSequence[dt.date],
+ weekmask: ArrayLike = ...,
+ holidays: None | ArrayLike | dt.date | _NestedSequence[dt.date] = ...,
+ busdaycal: None | busdaycalendar = ...,
+ out: None = ...,
+) -> NDArray[int_]: ...
+@overload
+def busday_count(
+ begindates: ArrayLike | dt.date | _NestedSequence[dt.date],
+ enddates: ArrayLike | dt.date | _NestedSequence[dt.date],
+ weekmask: ArrayLike = ...,
+ holidays: None | ArrayLike | dt.date | _NestedSequence[dt.date] = ...,
+ busdaycal: None | busdaycalendar = ...,
+ out: _ArrayType = ...,
+) -> _ArrayType: ...
+
+# `roll="raise"` is (more or less?) equivalent to `casting="safe"`
+@overload
+def busday_offset( # type: ignore[misc]
+ dates: datetime64 | dt.date,
+ offsets: _TD64Like_co | dt.timedelta,
+ roll: L["raise"] = ...,
+ weekmask: ArrayLike = ...,
+ holidays: None | ArrayLike | dt.date | _NestedSequence[dt.date] = ...,
+ busdaycal: None | busdaycalendar = ...,
+ out: None = ...,
+) -> datetime64: ...
+@overload
+def busday_offset( # type: ignore[misc]
+ dates: _ArrayLike[datetime64] | dt.date | _NestedSequence[dt.date],
+ offsets: _ArrayLikeTD64_co | dt.timedelta | _NestedSequence[dt.timedelta],
+ roll: L["raise"] = ...,
+ weekmask: ArrayLike = ...,
+ holidays: None | ArrayLike | dt.date | _NestedSequence[dt.date] = ...,
+ busdaycal: None | busdaycalendar = ...,
+ out: None = ...,
+) -> NDArray[datetime64]: ...
+@overload
+def busday_offset( # type: ignore[misc]
+ dates: _ArrayLike[datetime64] | dt.date | _NestedSequence[dt.date],
+ offsets: _ArrayLikeTD64_co | dt.timedelta | _NestedSequence[dt.timedelta],
+ roll: L["raise"] = ...,
+ weekmask: ArrayLike = ...,
+ holidays: None | ArrayLike | dt.date | _NestedSequence[dt.date] = ...,
+ busdaycal: None | busdaycalendar = ...,
+ out: _ArrayType = ...,
+) -> _ArrayType: ...
+@overload
+def busday_offset( # type: ignore[misc]
+ dates: _ScalarLike_co | dt.date,
+ offsets: _ScalarLike_co | dt.timedelta,
+ roll: _RollKind,
+ weekmask: ArrayLike = ...,
+ holidays: None | ArrayLike | dt.date | _NestedSequence[dt.date] = ...,
+ busdaycal: None | busdaycalendar = ...,
+ out: None = ...,
+) -> datetime64: ...
+@overload
+def busday_offset( # type: ignore[misc]
+ dates: ArrayLike | dt.date | _NestedSequence[dt.date],
+ offsets: ArrayLike | dt.timedelta | _NestedSequence[dt.timedelta],
+ roll: _RollKind,
+ weekmask: ArrayLike = ...,
+ holidays: None | ArrayLike | dt.date | _NestedSequence[dt.date] = ...,
+ busdaycal: None | busdaycalendar = ...,
+ out: None = ...,
+) -> NDArray[datetime64]: ...
+@overload
+def busday_offset(
+ dates: ArrayLike | dt.date | _NestedSequence[dt.date],
+ offsets: ArrayLike | dt.timedelta | _NestedSequence[dt.timedelta],
+ roll: _RollKind,
+ weekmask: ArrayLike = ...,
+ holidays: None | ArrayLike | dt.date | _NestedSequence[dt.date] = ...,
+ busdaycal: None | busdaycalendar = ...,
+ out: _ArrayType = ...,
+) -> _ArrayType: ...
+
+@overload
+def is_busday( # type: ignore[misc]
+ dates: _ScalarLike_co | dt.date,
+ weekmask: ArrayLike = ...,
+ holidays: None | ArrayLike | dt.date | _NestedSequence[dt.date] = ...,
+ busdaycal: None | busdaycalendar = ...,
+ out: None = ...,
+) -> np.bool: ...
+@overload
+def is_busday( # type: ignore[misc]
+ dates: ArrayLike | _NestedSequence[dt.date],
+ weekmask: ArrayLike = ...,
+ holidays: None | ArrayLike | dt.date | _NestedSequence[dt.date] = ...,
+ busdaycal: None | busdaycalendar = ...,
+ out: None = ...,
+) -> NDArray[np.bool]: ...
+@overload
+def is_busday(
+ dates: ArrayLike | _NestedSequence[dt.date],
+ weekmask: ArrayLike = ...,
+ holidays: None | ArrayLike | dt.date | _NestedSequence[dt.date] = ...,
+ busdaycal: None | busdaycalendar = ...,
+ out: _ArrayType = ...,
+) -> _ArrayType: ...
+
+@overload
+def datetime_as_string( # type: ignore[misc]
+ arr: datetime64 | dt.date,
+ unit: None | L["auto"] | _UnitKind = ...,
+ timezone: L["naive", "UTC", "local"] | dt.tzinfo = ...,
+ casting: _CastingKind = ...,
+) -> str_: ...
+@overload
+def datetime_as_string(
+ arr: _ArrayLikeDT64_co | _NestedSequence[dt.date],
+ unit: None | L["auto"] | _UnitKind = ...,
+ timezone: L["naive", "UTC", "local"] | dt.tzinfo = ...,
+ casting: _CastingKind = ...,
+) -> NDArray[str_]: ...
+
+@overload
+def compare_chararrays(
+ a1: _ArrayLikeStr_co,
+ a2: _ArrayLikeStr_co,
+ cmp: L["<", "<=", "==", ">=", ">", "!="],
+ rstrip: bool,
+) -> NDArray[np.bool]: ...
+@overload
+def compare_chararrays(
+ a1: _ArrayLikeBytes_co,
+ a2: _ArrayLikeBytes_co,
+ cmp: L["<", "<=", "==", ">=", ">", "!="],
+ rstrip: bool,
+) -> NDArray[np.bool]: ...
+
+def add_docstring(obj: Callable[..., Any], docstring: str, /) -> None: ...
+
+_GetItemKeys: TypeAlias = L[
+ "C", "CONTIGUOUS", "C_CONTIGUOUS",
+ "F", "FORTRAN", "F_CONTIGUOUS",
+ "W", "WRITEABLE",
+ "B", "BEHAVED",
+ "O", "OWNDATA",
+ "A", "ALIGNED",
+ "X", "WRITEBACKIFCOPY",
+ "CA", "CARRAY",
+ "FA", "FARRAY",
+ "FNC",
+ "FORC",
+]
+_SetItemKeys: TypeAlias = L[
+ "A", "ALIGNED",
+ "W", "WRITEABLE",
+ "X", "WRITEBACKIFCOPY",
+]
+
+@final
+class flagsobj:
+ __hash__: ClassVar[None] # type: ignore[assignment]
+ aligned: bool
+ # NOTE: deprecated
+ # updateifcopy: bool
+ writeable: bool
+ writebackifcopy: bool
+ @property
+ def behaved(self) -> bool: ...
+ @property
+ def c_contiguous(self) -> bool: ...
+ @property
+ def carray(self) -> bool: ...
+ @property
+ def contiguous(self) -> bool: ...
+ @property
+ def f_contiguous(self) -> bool: ...
+ @property
+ def farray(self) -> bool: ...
+ @property
+ def fnc(self) -> bool: ...
+ @property
+ def forc(self) -> bool: ...
+ @property
+ def fortran(self) -> bool: ...
+ @property
+ def num(self) -> int: ...
+ @property
+ def owndata(self) -> bool: ...
+ def __getitem__(self, key: _GetItemKeys) -> bool: ...
+ def __setitem__(self, key: _SetItemKeys, value: bool) -> None: ...
+
+def nested_iters(
+ op: ArrayLike | Sequence[ArrayLike],
+ axes: Sequence[Sequence[SupportsIndex]],
+ flags: None | Sequence[_NDIterFlagsKind] = ...,
+ op_flags: None | Sequence[Sequence[_NDIterFlagsOp]] = ...,
+ op_dtypes: DTypeLike | Sequence[DTypeLike] = ...,
+ order: _OrderKACF = ...,
+ casting: _CastingKind = ...,
+ buffersize: SupportsIndex = ...,
+) -> tuple[nditer, ...]: ...
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/numeric.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/numeric.py
new file mode 100644
index 0000000000000000000000000000000000000000..d4ca10a635dd8b226e87ecd7198e0274677010b7
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/numeric.py
@@ -0,0 +1,2713 @@
+import functools
+import itertools
+import operator
+import sys
+import warnings
+import numbers
+import builtins
+import math
+
+import numpy as np
+from . import multiarray
+from . import numerictypes as nt
+from .multiarray import (
+ ALLOW_THREADS, BUFSIZE, CLIP, MAXDIMS, MAY_SHARE_BOUNDS, MAY_SHARE_EXACT,
+ RAISE, WRAP, arange, array, asarray, asanyarray, ascontiguousarray,
+ asfortranarray, broadcast, can_cast, concatenate, copyto, dot, dtype,
+ empty, empty_like, flatiter, frombuffer, from_dlpack, fromfile, fromiter,
+ fromstring, inner, lexsort, matmul, may_share_memory, min_scalar_type,
+ ndarray, nditer, nested_iters, promote_types, putmask, result_type,
+ shares_memory, vdot, where, zeros, normalize_axis_index, vecdot
+)
+
+from . import overrides
+from . import umath
+from . import shape_base
+from .overrides import finalize_array_function_like, set_module
+from .umath import (multiply, invert, sin, PINF, NAN)
+from . import numerictypes
+from ..exceptions import AxisError
+from ._ufunc_config import errstate
+
+bitwise_not = invert
+ufunc = type(sin)
+newaxis = None
+
+array_function_dispatch = functools.partial(
+ overrides.array_function_dispatch, module='numpy')
+
+
+__all__ = [
+ 'newaxis', 'ndarray', 'flatiter', 'nditer', 'nested_iters', 'ufunc',
+ 'arange', 'array', 'asarray', 'asanyarray', 'ascontiguousarray',
+ 'asfortranarray', 'zeros', 'count_nonzero', 'empty', 'broadcast', 'dtype',
+ 'fromstring', 'fromfile', 'frombuffer', 'from_dlpack', 'where',
+ 'argwhere', 'copyto', 'concatenate', 'lexsort', 'astype',
+ 'can_cast', 'promote_types', 'min_scalar_type',
+ 'result_type', 'isfortran', 'empty_like', 'zeros_like', 'ones_like',
+ 'correlate', 'convolve', 'inner', 'dot', 'outer', 'vdot', 'roll',
+ 'rollaxis', 'moveaxis', 'cross', 'tensordot', 'little_endian',
+ 'fromiter', 'array_equal', 'array_equiv', 'indices', 'fromfunction',
+ 'isclose', 'isscalar', 'binary_repr', 'base_repr', 'ones',
+ 'identity', 'allclose', 'putmask',
+ 'flatnonzero', 'inf', 'nan', 'False_', 'True_', 'bitwise_not',
+ 'full', 'full_like', 'matmul', 'vecdot', 'shares_memory',
+ 'may_share_memory']
+
+
+def _zeros_like_dispatcher(
+ a, dtype=None, order=None, subok=None, shape=None, *, device=None
+):
+ return (a,)
+
+
+@array_function_dispatch(_zeros_like_dispatcher)
+def zeros_like(
+ a, dtype=None, order='K', subok=True, shape=None, *, device=None
+):
+ """
+ Return an array of zeros with the same shape and type as a given array.
+
+ Parameters
+ ----------
+ a : array_like
+ The shape and data-type of `a` define these same attributes of
+ the returned array.
+ dtype : data-type, optional
+ Overrides the data type of the result.
+ order : {'C', 'F', 'A', or 'K'}, optional
+ Overrides the memory layout of the result. 'C' means C-order,
+ 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
+ 'C' otherwise. 'K' means match the layout of `a` as closely
+ as possible.
+ subok : bool, optional.
+ If True, then the newly created array will use the sub-class
+ type of `a`, otherwise it will be a base-class array. Defaults
+ to True.
+ shape : int or sequence of ints, optional.
+ Overrides the shape of the result. If order='K' and the number of
+ dimensions is unchanged, will try to keep order, otherwise,
+ order='C' is implied.
+ device : str, optional
+ The device on which to place the created array. Default: None.
+ For Array-API interoperability only, so must be ``"cpu"`` if passed.
+
+ .. versionadded:: 2.0.0
+
+ Returns
+ -------
+ out : ndarray
+ Array of zeros with the same shape and type as `a`.
+
+ See Also
+ --------
+ empty_like : Return an empty array with shape and type of input.
+ ones_like : Return an array of ones with shape and type of input.
+ full_like : Return a new array with shape of input filled with value.
+ zeros : Return a new array setting values to zero.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.arange(6)
+ >>> x = x.reshape((2, 3))
+ >>> x
+ array([[0, 1, 2],
+ [3, 4, 5]])
+ >>> np.zeros_like(x)
+ array([[0, 0, 0],
+ [0, 0, 0]])
+
+ >>> y = np.arange(3, dtype=float)
+ >>> y
+ array([0., 1., 2.])
+ >>> np.zeros_like(y)
+ array([0., 0., 0.])
+
+ """
+ res = empty_like(
+ a, dtype=dtype, order=order, subok=subok, shape=shape, device=device
+ )
+ # needed instead of a 0 to get same result as zeros for string dtypes
+ z = zeros(1, dtype=res.dtype)
+ multiarray.copyto(res, z, casting='unsafe')
+ return res
+
+
+@finalize_array_function_like
+@set_module('numpy')
+def ones(shape, dtype=None, order='C', *, device=None, like=None):
+ """
+ Return a new array of given shape and type, filled with ones.
+
+ Parameters
+ ----------
+ shape : int or sequence of ints
+ Shape of the new array, e.g., ``(2, 3)`` or ``2``.
+ dtype : data-type, optional
+ The desired data-type for the array, e.g., `numpy.int8`. Default is
+ `numpy.float64`.
+ order : {'C', 'F'}, optional, default: C
+ Whether to store multi-dimensional data in row-major
+ (C-style) or column-major (Fortran-style) order in
+ memory.
+ device : str, optional
+ The device on which to place the created array. Default: None.
+ For Array-API interoperability only, so must be ``"cpu"`` if passed.
+
+ .. versionadded:: 2.0.0
+ ${ARRAY_FUNCTION_LIKE}
+
+ .. versionadded:: 1.20.0
+
+ Returns
+ -------
+ out : ndarray
+ Array of ones with the given shape, dtype, and order.
+
+ See Also
+ --------
+ ones_like : Return an array of ones with shape and type of input.
+ empty : Return a new uninitialized array.
+ zeros : Return a new array setting values to zero.
+ full : Return a new array of given shape filled with value.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.ones(5)
+ array([1., 1., 1., 1., 1.])
+
+ >>> np.ones((5,), dtype=int)
+ array([1, 1, 1, 1, 1])
+
+ >>> np.ones((2, 1))
+ array([[1.],
+ [1.]])
+
+ >>> s = (2,2)
+ >>> np.ones(s)
+ array([[1., 1.],
+ [1., 1.]])
+
+ """
+ if like is not None:
+ return _ones_with_like(
+ like, shape, dtype=dtype, order=order, device=device
+ )
+
+ a = empty(shape, dtype, order, device=device)
+ multiarray.copyto(a, 1, casting='unsafe')
+ return a
+
+
+_ones_with_like = array_function_dispatch()(ones)
+
+
+def _ones_like_dispatcher(
+ a, dtype=None, order=None, subok=None, shape=None, *, device=None
+):
+ return (a,)
+
+
+@array_function_dispatch(_ones_like_dispatcher)
+def ones_like(
+ a, dtype=None, order='K', subok=True, shape=None, *, device=None
+):
+ """
+ Return an array of ones with the same shape and type as a given array.
+
+ Parameters
+ ----------
+ a : array_like
+ The shape and data-type of `a` define these same attributes of
+ the returned array.
+ dtype : data-type, optional
+ Overrides the data type of the result.
+ order : {'C', 'F', 'A', or 'K'}, optional
+ Overrides the memory layout of the result. 'C' means C-order,
+ 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
+ 'C' otherwise. 'K' means match the layout of `a` as closely
+ as possible.
+ subok : bool, optional.
+ If True, then the newly created array will use the sub-class
+ type of `a`, otherwise it will be a base-class array. Defaults
+ to True.
+ shape : int or sequence of ints, optional.
+ Overrides the shape of the result. If order='K' and the number of
+ dimensions is unchanged, will try to keep order, otherwise,
+ order='C' is implied.
+ device : str, optional
+ The device on which to place the created array. Default: None.
+ For Array-API interoperability only, so must be ``"cpu"`` if passed.
+
+ .. versionadded:: 2.0.0
+
+ Returns
+ -------
+ out : ndarray
+ Array of ones with the same shape and type as `a`.
+
+ See Also
+ --------
+ empty_like : Return an empty array with shape and type of input.
+ zeros_like : Return an array of zeros with shape and type of input.
+ full_like : Return a new array with shape of input filled with value.
+ ones : Return a new array setting values to one.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.arange(6)
+ >>> x = x.reshape((2, 3))
+ >>> x
+ array([[0, 1, 2],
+ [3, 4, 5]])
+ >>> np.ones_like(x)
+ array([[1, 1, 1],
+ [1, 1, 1]])
+
+ >>> y = np.arange(3, dtype=float)
+ >>> y
+ array([0., 1., 2.])
+ >>> np.ones_like(y)
+ array([1., 1., 1.])
+
+ """
+ res = empty_like(
+ a, dtype=dtype, order=order, subok=subok, shape=shape, device=device
+ )
+ multiarray.copyto(res, 1, casting='unsafe')
+ return res
+
+
+def _full_dispatcher(
+ shape, fill_value, dtype=None, order=None, *, device=None, like=None
+):
+ return(like,)
+
+
+@finalize_array_function_like
+@set_module('numpy')
+def full(shape, fill_value, dtype=None, order='C', *, device=None, like=None):
+ """
+ Return a new array of given shape and type, filled with `fill_value`.
+
+ Parameters
+ ----------
+ shape : int or sequence of ints
+ Shape of the new array, e.g., ``(2, 3)`` or ``2``.
+ fill_value : scalar or array_like
+ Fill value.
+ dtype : data-type, optional
+ The desired data-type for the array The default, None, means
+ ``np.array(fill_value).dtype``.
+ order : {'C', 'F'}, optional
+ Whether to store multidimensional data in C- or Fortran-contiguous
+ (row- or column-wise) order in memory.
+ device : str, optional
+ The device on which to place the created array. Default: None.
+ For Array-API interoperability only, so must be ``"cpu"`` if passed.
+
+ .. versionadded:: 2.0.0
+ ${ARRAY_FUNCTION_LIKE}
+
+ .. versionadded:: 1.20.0
+
+ Returns
+ -------
+ out : ndarray
+ Array of `fill_value` with the given shape, dtype, and order.
+
+ See Also
+ --------
+ full_like : Return a new array with shape of input filled with value.
+ empty : Return a new uninitialized array.
+ ones : Return a new array setting values to one.
+ zeros : Return a new array setting values to zero.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.full((2, 2), np.inf)
+ array([[inf, inf],
+ [inf, inf]])
+ >>> np.full((2, 2), 10)
+ array([[10, 10],
+ [10, 10]])
+
+ >>> np.full((2, 2), [1, 2])
+ array([[1, 2],
+ [1, 2]])
+
+ """
+ if like is not None:
+ return _full_with_like(
+ like, shape, fill_value, dtype=dtype, order=order, device=device
+ )
+
+ if dtype is None:
+ fill_value = asarray(fill_value)
+ dtype = fill_value.dtype
+ a = empty(shape, dtype, order, device=device)
+ multiarray.copyto(a, fill_value, casting='unsafe')
+ return a
+
+
+_full_with_like = array_function_dispatch()(full)
+
+
+def _full_like_dispatcher(
+ a, fill_value, dtype=None, order=None, subok=None, shape=None,
+ *, device=None
+):
+ return (a,)
+
+
+@array_function_dispatch(_full_like_dispatcher)
+def full_like(
+ a, fill_value, dtype=None, order='K', subok=True, shape=None,
+ *, device=None
+):
+ """
+ Return a full array with the same shape and type as a given array.
+
+ Parameters
+ ----------
+ a : array_like
+ The shape and data-type of `a` define these same attributes of
+ the returned array.
+ fill_value : array_like
+ Fill value.
+ dtype : data-type, optional
+ Overrides the data type of the result.
+ order : {'C', 'F', 'A', or 'K'}, optional
+ Overrides the memory layout of the result. 'C' means C-order,
+ 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
+ 'C' otherwise. 'K' means match the layout of `a` as closely
+ as possible.
+ subok : bool, optional.
+ If True, then the newly created array will use the sub-class
+ type of `a`, otherwise it will be a base-class array. Defaults
+ to True.
+ shape : int or sequence of ints, optional.
+ Overrides the shape of the result. If order='K' and the number of
+ dimensions is unchanged, will try to keep order, otherwise,
+ order='C' is implied.
+ device : str, optional
+ The device on which to place the created array. Default: None.
+ For Array-API interoperability only, so must be ``"cpu"`` if passed.
+
+ .. versionadded:: 2.0.0
+
+ Returns
+ -------
+ out : ndarray
+ Array of `fill_value` with the same shape and type as `a`.
+
+ See Also
+ --------
+ empty_like : Return an empty array with shape and type of input.
+ ones_like : Return an array of ones with shape and type of input.
+ zeros_like : Return an array of zeros with shape and type of input.
+ full : Return a new array of given shape filled with value.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.arange(6, dtype=int)
+ >>> np.full_like(x, 1)
+ array([1, 1, 1, 1, 1, 1])
+ >>> np.full_like(x, 0.1)
+ array([0, 0, 0, 0, 0, 0])
+ >>> np.full_like(x, 0.1, dtype=np.double)
+ array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
+ >>> np.full_like(x, np.nan, dtype=np.double)
+ array([nan, nan, nan, nan, nan, nan])
+
+ >>> y = np.arange(6, dtype=np.double)
+ >>> np.full_like(y, 0.1)
+ array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
+
+ >>> y = np.zeros([2, 2, 3], dtype=int)
+ >>> np.full_like(y, [0, 0, 255])
+ array([[[ 0, 0, 255],
+ [ 0, 0, 255]],
+ [[ 0, 0, 255],
+ [ 0, 0, 255]]])
+ """
+ res = empty_like(
+ a, dtype=dtype, order=order, subok=subok, shape=shape, device=device
+ )
+ multiarray.copyto(res, fill_value, casting='unsafe')
+ return res
+
+
+def _count_nonzero_dispatcher(a, axis=None, *, keepdims=None):
+ return (a,)
+
+
+@array_function_dispatch(_count_nonzero_dispatcher)
+def count_nonzero(a, axis=None, *, keepdims=False):
+ """
+ Counts the number of non-zero values in the array ``a``.
+
+ The word "non-zero" is in reference to the Python 2.x
+ built-in method ``__nonzero__()`` (renamed ``__bool__()``
+ in Python 3.x) of Python objects that tests an object's
+ "truthfulness". For example, any number is considered
+ truthful if it is nonzero, whereas any string is considered
+ truthful if it is not the empty string. Thus, this function
+ (recursively) counts how many elements in ``a`` (and in
+ sub-arrays thereof) have their ``__nonzero__()`` or ``__bool__()``
+ method evaluated to ``True``.
+
+ Parameters
+ ----------
+ a : array_like
+ The array for which to count non-zeros.
+ axis : int or tuple, optional
+ Axis or tuple of axes along which to count non-zeros.
+ Default is None, meaning that non-zeros will be counted
+ along a flattened version of ``a``.
+ keepdims : bool, optional
+ If this is set to True, the axes that are counted are left
+ in the result as dimensions with size one. With this option,
+ the result will broadcast correctly against the input array.
+
+ Returns
+ -------
+ count : int or array of int
+ Number of non-zero values in the array along a given axis.
+ Otherwise, the total number of non-zero values in the array
+ is returned.
+
+ See Also
+ --------
+ nonzero : Return the coordinates of all the non-zero values.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.count_nonzero(np.eye(4))
+ 4
+ >>> a = np.array([[0, 1, 7, 0],
+ ... [3, 0, 2, 19]])
+ >>> np.count_nonzero(a)
+ 5
+ >>> np.count_nonzero(a, axis=0)
+ array([1, 1, 2, 1])
+ >>> np.count_nonzero(a, axis=1)
+ array([2, 3])
+ >>> np.count_nonzero(a, axis=1, keepdims=True)
+ array([[2],
+ [3]])
+ """
+ if axis is None and not keepdims:
+ return multiarray.count_nonzero(a)
+
+ a = asanyarray(a)
+
+ # TODO: this works around .astype(bool) not working properly (gh-9847)
+ if np.issubdtype(a.dtype, np.character):
+ a_bool = a != a.dtype.type()
+ else:
+ a_bool = a.astype(np.bool, copy=False)
+
+ return a_bool.sum(axis=axis, dtype=np.intp, keepdims=keepdims)
+
+
+@set_module('numpy')
+def isfortran(a):
+ """
+ Check if the array is Fortran contiguous but *not* C contiguous.
+
+ This function is obsolete. If you only want to check if an array is Fortran
+ contiguous use ``a.flags.f_contiguous`` instead.
+
+ Parameters
+ ----------
+ a : ndarray
+ Input array.
+
+ Returns
+ -------
+ isfortran : bool
+ Returns True if the array is Fortran contiguous but *not* C contiguous.
+
+
+ Examples
+ --------
+
+ np.array allows to specify whether the array is written in C-contiguous
+ order (last index varies the fastest), or FORTRAN-contiguous order in
+ memory (first index varies the fastest).
+
+ >>> import numpy as np
+ >>> a = np.array([[1, 2, 3], [4, 5, 6]], order='C')
+ >>> a
+ array([[1, 2, 3],
+ [4, 5, 6]])
+ >>> np.isfortran(a)
+ False
+
+ >>> b = np.array([[1, 2, 3], [4, 5, 6]], order='F')
+ >>> b
+ array([[1, 2, 3],
+ [4, 5, 6]])
+ >>> np.isfortran(b)
+ True
+
+
+ The transpose of a C-ordered array is a FORTRAN-ordered array.
+
+ >>> a = np.array([[1, 2, 3], [4, 5, 6]], order='C')
+ >>> a
+ array([[1, 2, 3],
+ [4, 5, 6]])
+ >>> np.isfortran(a)
+ False
+ >>> b = a.T
+ >>> b
+ array([[1, 4],
+ [2, 5],
+ [3, 6]])
+ >>> np.isfortran(b)
+ True
+
+ C-ordered arrays evaluate as False even if they are also FORTRAN-ordered.
+
+ >>> np.isfortran(np.array([1, 2], order='F'))
+ False
+
+ """
+ return a.flags.fnc
+
+
+def _argwhere_dispatcher(a):
+ return (a,)
+
+
+@array_function_dispatch(_argwhere_dispatcher)
+def argwhere(a):
+ """
+ Find the indices of array elements that are non-zero, grouped by element.
+
+ Parameters
+ ----------
+ a : array_like
+ Input data.
+
+ Returns
+ -------
+ index_array : (N, a.ndim) ndarray
+ Indices of elements that are non-zero. Indices are grouped by element.
+ This array will have shape ``(N, a.ndim)`` where ``N`` is the number of
+ non-zero items.
+
+ See Also
+ --------
+ where, nonzero
+
+ Notes
+ -----
+ ``np.argwhere(a)`` is almost the same as ``np.transpose(np.nonzero(a))``,
+ but produces a result of the correct shape for a 0D array.
+
+ The output of ``argwhere`` is not suitable for indexing arrays.
+ For this purpose use ``nonzero(a)`` instead.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.arange(6).reshape(2,3)
+ >>> x
+ array([[0, 1, 2],
+ [3, 4, 5]])
+ >>> np.argwhere(x>1)
+ array([[0, 2],
+ [1, 0],
+ [1, 1],
+ [1, 2]])
+
+ """
+ # nonzero does not behave well on 0d, so promote to 1d
+ if np.ndim(a) == 0:
+ a = shape_base.atleast_1d(a)
+ # then remove the added dimension
+ return argwhere(a)[:, :0]
+ return transpose(nonzero(a))
+
+
+def _flatnonzero_dispatcher(a):
+ return (a,)
+
+
+@array_function_dispatch(_flatnonzero_dispatcher)
+def flatnonzero(a):
+ """
+ Return indices that are non-zero in the flattened version of a.
+
+ This is equivalent to ``np.nonzero(np.ravel(a))[0]``.
+
+ Parameters
+ ----------
+ a : array_like
+ Input data.
+
+ Returns
+ -------
+ res : ndarray
+ Output array, containing the indices of the elements of ``a.ravel()``
+ that are non-zero.
+
+ See Also
+ --------
+ nonzero : Return the indices of the non-zero elements of the input array.
+ ravel : Return a 1-D array containing the elements of the input array.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.arange(-2, 3)
+ >>> x
+ array([-2, -1, 0, 1, 2])
+ >>> np.flatnonzero(x)
+ array([0, 1, 3, 4])
+
+ Use the indices of the non-zero elements as an index array to extract
+ these elements:
+
+ >>> x.ravel()[np.flatnonzero(x)]
+ array([-2, -1, 1, 2])
+
+ """
+ return np.nonzero(np.ravel(a))[0]
+
+
+def _correlate_dispatcher(a, v, mode=None):
+ return (a, v)
+
+
+@array_function_dispatch(_correlate_dispatcher)
+def correlate(a, v, mode='valid'):
+ r"""
+ Cross-correlation of two 1-dimensional sequences.
+
+ This function computes the correlation as generally defined in signal
+ processing texts [1]_:
+
+ .. math:: c_k = \sum_n a_{n+k} \cdot \overline{v}_n
+
+ with a and v sequences being zero-padded where necessary and
+ :math:`\overline v` denoting complex conjugation.
+
+ Parameters
+ ----------
+ a, v : array_like
+ Input sequences.
+ mode : {'valid', 'same', 'full'}, optional
+ Refer to the `convolve` docstring. Note that the default
+ is 'valid', unlike `convolve`, which uses 'full'.
+
+ Returns
+ -------
+ out : ndarray
+ Discrete cross-correlation of `a` and `v`.
+
+ See Also
+ --------
+ convolve : Discrete, linear convolution of two one-dimensional sequences.
+ scipy.signal.correlate : uses FFT which has superior performance
+ on large arrays.
+
+ Notes
+ -----
+ The definition of correlation above is not unique and sometimes
+ correlation may be defined differently. Another common definition is [1]_:
+
+ .. math:: c'_k = \sum_n a_{n} \cdot \overline{v_{n+k}}
+
+ which is related to :math:`c_k` by :math:`c'_k = c_{-k}`.
+
+ `numpy.correlate` may perform slowly in large arrays (i.e. n = 1e5)
+ because it does not use the FFT to compute the convolution; in that case,
+ `scipy.signal.correlate` might be preferable.
+
+ References
+ ----------
+ .. [1] Wikipedia, "Cross-correlation",
+ https://en.wikipedia.org/wiki/Cross-correlation
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.correlate([1, 2, 3], [0, 1, 0.5])
+ array([3.5])
+ >>> np.correlate([1, 2, 3], [0, 1, 0.5], "same")
+ array([2. , 3.5, 3. ])
+ >>> np.correlate([1, 2, 3], [0, 1, 0.5], "full")
+ array([0.5, 2. , 3.5, 3. , 0. ])
+
+ Using complex sequences:
+
+ >>> np.correlate([1+1j, 2, 3-1j], [0, 1, 0.5j], 'full')
+ array([ 0.5-0.5j, 1.0+0.j , 1.5-1.5j, 3.0-1.j , 0.0+0.j ])
+
+ Note that you get the time reversed, complex conjugated result
+ (:math:`\overline{c_{-k}}`) when the two input sequences a and v change
+ places:
+
+ >>> np.correlate([0, 1, 0.5j], [1+1j, 2, 3-1j], 'full')
+ array([ 0.0+0.j , 3.0+1.j , 1.5+1.5j, 1.0+0.j , 0.5+0.5j])
+
+ """
+ return multiarray.correlate2(a, v, mode)
+
+
+def _convolve_dispatcher(a, v, mode=None):
+ return (a, v)
+
+
+@array_function_dispatch(_convolve_dispatcher)
+def convolve(a, v, mode='full'):
+ """
+ Returns the discrete, linear convolution of two one-dimensional sequences.
+
+ The convolution operator is often seen in signal processing, where it
+ models the effect of a linear time-invariant system on a signal [1]_. In
+ probability theory, the sum of two independent random variables is
+ distributed according to the convolution of their individual
+ distributions.
+
+ If `v` is longer than `a`, the arrays are swapped before computation.
+
+ Parameters
+ ----------
+ a : (N,) array_like
+ First one-dimensional input array.
+ v : (M,) array_like
+ Second one-dimensional input array.
+ mode : {'full', 'valid', 'same'}, optional
+ 'full':
+ By default, mode is 'full'. This returns the convolution
+ at each point of overlap, with an output shape of (N+M-1,). At
+ the end-points of the convolution, the signals do not overlap
+ completely, and boundary effects may be seen.
+
+ 'same':
+ Mode 'same' returns output of length ``max(M, N)``. Boundary
+ effects are still visible.
+
+ 'valid':
+ Mode 'valid' returns output of length
+ ``max(M, N) - min(M, N) + 1``. The convolution product is only given
+ for points where the signals overlap completely. Values outside
+ the signal boundary have no effect.
+
+ Returns
+ -------
+ out : ndarray
+ Discrete, linear convolution of `a` and `v`.
+
+ See Also
+ --------
+ scipy.signal.fftconvolve : Convolve two arrays using the Fast Fourier
+ Transform.
+ scipy.linalg.toeplitz : Used to construct the convolution operator.
+ polymul : Polynomial multiplication. Same output as convolve, but also
+ accepts poly1d objects as input.
+
+ Notes
+ -----
+ The discrete convolution operation is defined as
+
+ .. math:: (a * v)_n = \\sum_{m = -\\infty}^{\\infty} a_m v_{n - m}
+
+ It can be shown that a convolution :math:`x(t) * y(t)` in time/space
+ is equivalent to the multiplication :math:`X(f) Y(f)` in the Fourier
+ domain, after appropriate padding (padding is necessary to prevent
+ circular convolution). Since multiplication is more efficient (faster)
+ than convolution, the function `scipy.signal.fftconvolve` exploits the
+ FFT to calculate the convolution of large data-sets.
+
+ References
+ ----------
+ .. [1] Wikipedia, "Convolution",
+ https://en.wikipedia.org/wiki/Convolution
+
+ Examples
+ --------
+ Note how the convolution operator flips the second array
+ before "sliding" the two across one another:
+
+ >>> import numpy as np
+ >>> np.convolve([1, 2, 3], [0, 1, 0.5])
+ array([0. , 1. , 2.5, 4. , 1.5])
+
+ Only return the middle values of the convolution.
+ Contains boundary effects, where zeros are taken
+ into account:
+
+ >>> np.convolve([1,2,3],[0,1,0.5], 'same')
+ array([1. , 2.5, 4. ])
+
+ The two arrays are of the same length, so there
+ is only one position where they completely overlap:
+
+ >>> np.convolve([1,2,3],[0,1,0.5], 'valid')
+ array([2.5])
+
+ """
+ a, v = array(a, copy=None, ndmin=1), array(v, copy=None, ndmin=1)
+ if (len(v) > len(a)):
+ a, v = v, a
+ if len(a) == 0:
+ raise ValueError('a cannot be empty')
+ if len(v) == 0:
+ raise ValueError('v cannot be empty')
+ return multiarray.correlate(a, v[::-1], mode)
+
+
+def _outer_dispatcher(a, b, out=None):
+ return (a, b, out)
+
+
+@array_function_dispatch(_outer_dispatcher)
+def outer(a, b, out=None):
+ """
+ Compute the outer product of two vectors.
+
+ Given two vectors `a` and `b` of length ``M`` and ``N``, respectively,
+ the outer product [1]_ is::
+
+ [[a_0*b_0 a_0*b_1 ... a_0*b_{N-1} ]
+ [a_1*b_0 .
+ [ ... .
+ [a_{M-1}*b_0 a_{M-1}*b_{N-1} ]]
+
+ Parameters
+ ----------
+ a : (M,) array_like
+ First input vector. Input is flattened if
+ not already 1-dimensional.
+ b : (N,) array_like
+ Second input vector. Input is flattened if
+ not already 1-dimensional.
+ out : (M, N) ndarray, optional
+ A location where the result is stored
+
+ Returns
+ -------
+ out : (M, N) ndarray
+ ``out[i, j] = a[i] * b[j]``
+
+ See also
+ --------
+ inner
+ einsum : ``einsum('i,j->ij', a.ravel(), b.ravel())`` is the equivalent.
+ ufunc.outer : A generalization to dimensions other than 1D and other
+ operations. ``np.multiply.outer(a.ravel(), b.ravel())``
+ is the equivalent.
+ linalg.outer : An Array API compatible variation of ``np.outer``,
+ which accepts 1-dimensional inputs only.
+ tensordot : ``np.tensordot(a.ravel(), b.ravel(), axes=((), ()))``
+ is the equivalent.
+
+ References
+ ----------
+ .. [1] G. H. Golub and C. F. Van Loan, *Matrix Computations*, 3rd
+ ed., Baltimore, MD, Johns Hopkins University Press, 1996,
+ pg. 8.
+
+ Examples
+ --------
+ Make a (*very* coarse) grid for computing a Mandelbrot set:
+
+ >>> import numpy as np
+ >>> rl = np.outer(np.ones((5,)), np.linspace(-2, 2, 5))
+ >>> rl
+ array([[-2., -1., 0., 1., 2.],
+ [-2., -1., 0., 1., 2.],
+ [-2., -1., 0., 1., 2.],
+ [-2., -1., 0., 1., 2.],
+ [-2., -1., 0., 1., 2.]])
+ >>> im = np.outer(1j*np.linspace(2, -2, 5), np.ones((5,)))
+ >>> im
+ array([[0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j],
+ [0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j],
+ [0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j],
+ [0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j],
+ [0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j]])
+ >>> grid = rl + im
+ >>> grid
+ array([[-2.+2.j, -1.+2.j, 0.+2.j, 1.+2.j, 2.+2.j],
+ [-2.+1.j, -1.+1.j, 0.+1.j, 1.+1.j, 2.+1.j],
+ [-2.+0.j, -1.+0.j, 0.+0.j, 1.+0.j, 2.+0.j],
+ [-2.-1.j, -1.-1.j, 0.-1.j, 1.-1.j, 2.-1.j],
+ [-2.-2.j, -1.-2.j, 0.-2.j, 1.-2.j, 2.-2.j]])
+
+ An example using a "vector" of letters:
+
+ >>> x = np.array(['a', 'b', 'c'], dtype=object)
+ >>> np.outer(x, [1, 2, 3])
+ array([['a', 'aa', 'aaa'],
+ ['b', 'bb', 'bbb'],
+ ['c', 'cc', 'ccc']], dtype=object)
+
+ """
+ a = asarray(a)
+ b = asarray(b)
+ return multiply(a.ravel()[:, newaxis], b.ravel()[newaxis, :], out)
+
+
+def _tensordot_dispatcher(a, b, axes=None):
+ return (a, b)
+
+
+@array_function_dispatch(_tensordot_dispatcher)
+def tensordot(a, b, axes=2):
+ """
+ Compute tensor dot product along specified axes.
+
+ Given two tensors, `a` and `b`, and an array_like object containing
+ two array_like objects, ``(a_axes, b_axes)``, sum the products of
+ `a`'s and `b`'s elements (components) over the axes specified by
+ ``a_axes`` and ``b_axes``. The third argument can be a single non-negative
+ integer_like scalar, ``N``; if it is such, then the last ``N`` dimensions
+ of `a` and the first ``N`` dimensions of `b` are summed over.
+
+ Parameters
+ ----------
+ a, b : array_like
+ Tensors to "dot".
+
+ axes : int or (2,) array_like
+ * integer_like
+ If an int N, sum over the last N axes of `a` and the first N axes
+ of `b` in order. The sizes of the corresponding axes must match.
+ * (2,) array_like
+ Or, a list of axes to be summed over, first sequence applying to `a`,
+ second to `b`. Both elements array_like must be of the same length.
+
+ Returns
+ -------
+ output : ndarray
+ The tensor dot product of the input.
+
+ See Also
+ --------
+ dot, einsum
+
+ Notes
+ -----
+ Three common use cases are:
+ * ``axes = 0`` : tensor product :math:`a\\otimes b`
+ * ``axes = 1`` : tensor dot product :math:`a\\cdot b`
+ * ``axes = 2`` : (default) tensor double contraction :math:`a:b`
+
+ When `axes` is integer_like, the sequence of axes for evaluation
+ will be: from the -Nth axis to the -1th axis in `a`,
+ and from the 0th axis to (N-1)th axis in `b`.
+ For example, ``axes = 2`` is the equal to
+ ``axes = [[-2, -1], [0, 1]]``.
+ When N-1 is smaller than 0, or when -N is larger than -1,
+ the element of `a` and `b` are defined as the `axes`.
+
+ When there is more than one axis to sum over - and they are not the last
+ (first) axes of `a` (`b`) - the argument `axes` should consist of
+ two sequences of the same length, with the first axis to sum over given
+ first in both sequences, the second axis second, and so forth.
+ The calculation can be referred to ``numpy.einsum``.
+
+ The shape of the result consists of the non-contracted axes of the
+ first tensor, followed by the non-contracted axes of the second.
+
+ Examples
+ --------
+ An example on integer_like:
+
+ >>> a_0 = np.array([[1, 2], [3, 4]])
+ >>> b_0 = np.array([[5, 6], [7, 8]])
+ >>> c_0 = np.tensordot(a_0, b_0, axes=0)
+ >>> c_0.shape
+ (2, 2, 2, 2)
+ >>> c_0
+ array([[[[ 5, 6],
+ [ 7, 8]],
+ [[10, 12],
+ [14, 16]]],
+ [[[15, 18],
+ [21, 24]],
+ [[20, 24],
+ [28, 32]]]])
+
+ An example on array_like:
+
+ >>> a = np.arange(60.).reshape(3,4,5)
+ >>> b = np.arange(24.).reshape(4,3,2)
+ >>> c = np.tensordot(a,b, axes=([1,0],[0,1]))
+ >>> c.shape
+ (5, 2)
+ >>> c
+ array([[4400., 4730.],
+ [4532., 4874.],
+ [4664., 5018.],
+ [4796., 5162.],
+ [4928., 5306.]])
+
+ A slower but equivalent way of computing the same...
+
+ >>> d = np.zeros((5,2))
+ >>> for i in range(5):
+ ... for j in range(2):
+ ... for k in range(3):
+ ... for n in range(4):
+ ... d[i,j] += a[k,n,i] * b[n,k,j]
+ >>> c == d
+ array([[ True, True],
+ [ True, True],
+ [ True, True],
+ [ True, True],
+ [ True, True]])
+
+ An extended example taking advantage of the overloading of + and \\*:
+
+ >>> a = np.array(range(1, 9))
+ >>> a.shape = (2, 2, 2)
+ >>> A = np.array(('a', 'b', 'c', 'd'), dtype=object)
+ >>> A.shape = (2, 2)
+ >>> a; A
+ array([[[1, 2],
+ [3, 4]],
+ [[5, 6],
+ [7, 8]]])
+ array([['a', 'b'],
+ ['c', 'd']], dtype=object)
+
+ >>> np.tensordot(a, A) # third argument default is 2 for double-contraction
+ array(['abbcccdddd', 'aaaaabbbbbbcccccccdddddddd'], dtype=object)
+
+ >>> np.tensordot(a, A, 1)
+ array([[['acc', 'bdd'],
+ ['aaacccc', 'bbbdddd']],
+ [['aaaaacccccc', 'bbbbbdddddd'],
+ ['aaaaaaacccccccc', 'bbbbbbbdddddddd']]], dtype=object)
+
+ >>> np.tensordot(a, A, 0) # tensor product (result too long to incl.)
+ array([[[[['a', 'b'],
+ ['c', 'd']],
+ ...
+
+ >>> np.tensordot(a, A, (0, 1))
+ array([[['abbbbb', 'cddddd'],
+ ['aabbbbbb', 'ccdddddd']],
+ [['aaabbbbbbb', 'cccddddddd'],
+ ['aaaabbbbbbbb', 'ccccdddddddd']]], dtype=object)
+
+ >>> np.tensordot(a, A, (2, 1))
+ array([[['abb', 'cdd'],
+ ['aaabbbb', 'cccdddd']],
+ [['aaaaabbbbbb', 'cccccdddddd'],
+ ['aaaaaaabbbbbbbb', 'cccccccdddddddd']]], dtype=object)
+
+ >>> np.tensordot(a, A, ((0, 1), (0, 1)))
+ array(['abbbcccccddddddd', 'aabbbbccccccdddddddd'], dtype=object)
+
+ >>> np.tensordot(a, A, ((2, 1), (1, 0)))
+ array(['acccbbdddd', 'aaaaacccccccbbbbbbdddddddd'], dtype=object)
+
+ """
+ try:
+ iter(axes)
+ except Exception:
+ axes_a = list(range(-axes, 0))
+ axes_b = list(range(0, axes))
+ else:
+ axes_a, axes_b = axes
+ try:
+ na = len(axes_a)
+ axes_a = list(axes_a)
+ except TypeError:
+ axes_a = [axes_a]
+ na = 1
+ try:
+ nb = len(axes_b)
+ axes_b = list(axes_b)
+ except TypeError:
+ axes_b = [axes_b]
+ nb = 1
+
+ a, b = asarray(a), asarray(b)
+ as_ = a.shape
+ nda = a.ndim
+ bs = b.shape
+ ndb = b.ndim
+ equal = True
+ if na != nb:
+ equal = False
+ else:
+ for k in range(na):
+ if as_[axes_a[k]] != bs[axes_b[k]]:
+ equal = False
+ break
+ if axes_a[k] < 0:
+ axes_a[k] += nda
+ if axes_b[k] < 0:
+ axes_b[k] += ndb
+ if not equal:
+ raise ValueError("shape-mismatch for sum")
+
+ # Move the axes to sum over to the end of "a"
+ # and to the front of "b"
+ notin = [k for k in range(nda) if k not in axes_a]
+ newaxes_a = notin + axes_a
+ N2 = math.prod(as_[axis] for axis in axes_a)
+ newshape_a = (math.prod([as_[ax] for ax in notin]), N2)
+ olda = [as_[axis] for axis in notin]
+
+ notin = [k for k in range(ndb) if k not in axes_b]
+ newaxes_b = axes_b + notin
+ N2 = math.prod(bs[axis] for axis in axes_b)
+ newshape_b = (N2, math.prod([bs[ax] for ax in notin]))
+ oldb = [bs[axis] for axis in notin]
+
+ at = a.transpose(newaxes_a).reshape(newshape_a)
+ bt = b.transpose(newaxes_b).reshape(newshape_b)
+ res = dot(at, bt)
+ return res.reshape(olda + oldb)
+
+
+def _roll_dispatcher(a, shift, axis=None):
+ return (a,)
+
+
+@array_function_dispatch(_roll_dispatcher)
+def roll(a, shift, axis=None):
+ """
+ Roll array elements along a given axis.
+
+ Elements that roll beyond the last position are re-introduced at
+ the first.
+
+ Parameters
+ ----------
+ a : array_like
+ Input array.
+ shift : int or tuple of ints
+ The number of places by which elements are shifted. If a tuple,
+ then `axis` must be a tuple of the same size, and each of the
+ given axes is shifted by the corresponding number. If an int
+ while `axis` is a tuple of ints, then the same value is used for
+ all given axes.
+ axis : int or tuple of ints, optional
+ Axis or axes along which elements are shifted. By default, the
+ array is flattened before shifting, after which the original
+ shape is restored.
+
+ Returns
+ -------
+ res : ndarray
+ Output array, with the same shape as `a`.
+
+ See Also
+ --------
+ rollaxis : Roll the specified axis backwards, until it lies in a
+ given position.
+
+ Notes
+ -----
+ Supports rolling over multiple dimensions simultaneously.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.arange(10)
+ >>> np.roll(x, 2)
+ array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7])
+ >>> np.roll(x, -2)
+ array([2, 3, 4, 5, 6, 7, 8, 9, 0, 1])
+
+ >>> x2 = np.reshape(x, (2, 5))
+ >>> x2
+ array([[0, 1, 2, 3, 4],
+ [5, 6, 7, 8, 9]])
+ >>> np.roll(x2, 1)
+ array([[9, 0, 1, 2, 3],
+ [4, 5, 6, 7, 8]])
+ >>> np.roll(x2, -1)
+ array([[1, 2, 3, 4, 5],
+ [6, 7, 8, 9, 0]])
+ >>> np.roll(x2, 1, axis=0)
+ array([[5, 6, 7, 8, 9],
+ [0, 1, 2, 3, 4]])
+ >>> np.roll(x2, -1, axis=0)
+ array([[5, 6, 7, 8, 9],
+ [0, 1, 2, 3, 4]])
+ >>> np.roll(x2, 1, axis=1)
+ array([[4, 0, 1, 2, 3],
+ [9, 5, 6, 7, 8]])
+ >>> np.roll(x2, -1, axis=1)
+ array([[1, 2, 3, 4, 0],
+ [6, 7, 8, 9, 5]])
+ >>> np.roll(x2, (1, 1), axis=(1, 0))
+ array([[9, 5, 6, 7, 8],
+ [4, 0, 1, 2, 3]])
+ >>> np.roll(x2, (2, 1), axis=(1, 0))
+ array([[8, 9, 5, 6, 7],
+ [3, 4, 0, 1, 2]])
+
+ """
+ a = asanyarray(a)
+ if axis is None:
+ return roll(a.ravel(), shift, 0).reshape(a.shape)
+
+ else:
+ axis = normalize_axis_tuple(axis, a.ndim, allow_duplicate=True)
+ broadcasted = broadcast(shift, axis)
+ if broadcasted.ndim > 1:
+ raise ValueError(
+ "'shift' and 'axis' should be scalars or 1D sequences")
+ shifts = {ax: 0 for ax in range(a.ndim)}
+ for sh, ax in broadcasted:
+ shifts[ax] += int(sh)
+
+ rolls = [((slice(None), slice(None)),)] * a.ndim
+ for ax, offset in shifts.items():
+ offset %= a.shape[ax] or 1 # If `a` is empty, nothing matters.
+ if offset:
+ # (original, result), (original, result)
+ rolls[ax] = ((slice(None, -offset), slice(offset, None)),
+ (slice(-offset, None), slice(None, offset)))
+
+ result = empty_like(a)
+ for indices in itertools.product(*rolls):
+ arr_index, res_index = zip(*indices)
+ result[res_index] = a[arr_index]
+
+ return result
+
+
+def _rollaxis_dispatcher(a, axis, start=None):
+ return (a,)
+
+
+@array_function_dispatch(_rollaxis_dispatcher)
+def rollaxis(a, axis, start=0):
+ """
+ Roll the specified axis backwards, until it lies in a given position.
+
+ This function continues to be supported for backward compatibility, but you
+ should prefer `moveaxis`. The `moveaxis` function was added in NumPy
+ 1.11.
+
+ Parameters
+ ----------
+ a : ndarray
+ Input array.
+ axis : int
+ The axis to be rolled. The positions of the other axes do not
+ change relative to one another.
+ start : int, optional
+ When ``start <= axis``, the axis is rolled back until it lies in
+ this position. When ``start > axis``, the axis is rolled until it
+ lies before this position. The default, 0, results in a "complete"
+ roll. The following table describes how negative values of ``start``
+ are interpreted:
+
+ .. table::
+ :align: left
+
+ +-------------------+----------------------+
+ | ``start`` | Normalized ``start`` |
+ +===================+======================+
+ | ``-(arr.ndim+1)`` | raise ``AxisError`` |
+ +-------------------+----------------------+
+ | ``-arr.ndim`` | 0 |
+ +-------------------+----------------------+
+ | |vdots| | |vdots| |
+ +-------------------+----------------------+
+ | ``-1`` | ``arr.ndim-1`` |
+ +-------------------+----------------------+
+ | ``0`` | ``0`` |
+ +-------------------+----------------------+
+ | |vdots| | |vdots| |
+ +-------------------+----------------------+
+ | ``arr.ndim`` | ``arr.ndim`` |
+ +-------------------+----------------------+
+ | ``arr.ndim + 1`` | raise ``AxisError`` |
+ +-------------------+----------------------+
+
+ .. |vdots| unicode:: U+22EE .. Vertical Ellipsis
+
+ Returns
+ -------
+ res : ndarray
+ For NumPy >= 1.10.0 a view of `a` is always returned. For earlier
+ NumPy versions a view of `a` is returned only if the order of the
+ axes is changed, otherwise the input array is returned.
+
+ See Also
+ --------
+ moveaxis : Move array axes to new positions.
+ roll : Roll the elements of an array by a number of positions along a
+ given axis.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.ones((3,4,5,6))
+ >>> np.rollaxis(a, 3, 1).shape
+ (3, 6, 4, 5)
+ >>> np.rollaxis(a, 2).shape
+ (5, 3, 4, 6)
+ >>> np.rollaxis(a, 1, 4).shape
+ (3, 5, 6, 4)
+
+ """
+ n = a.ndim
+ axis = normalize_axis_index(axis, n)
+ if start < 0:
+ start += n
+ msg = "'%s' arg requires %d <= %s < %d, but %d was passed in"
+ if not (0 <= start < n + 1):
+ raise AxisError(msg % ('start', -n, 'start', n + 1, start))
+ if axis < start:
+ # it's been removed
+ start -= 1
+ if axis == start:
+ return a[...]
+ axes = list(range(0, n))
+ axes.remove(axis)
+ axes.insert(start, axis)
+ return a.transpose(axes)
+
+
+@set_module("numpy.lib.array_utils")
+def normalize_axis_tuple(axis, ndim, argname=None, allow_duplicate=False):
+ """
+ Normalizes an axis argument into a tuple of non-negative integer axes.
+
+ This handles shorthands such as ``1`` and converts them to ``(1,)``,
+ as well as performing the handling of negative indices covered by
+ `normalize_axis_index`.
+
+ By default, this forbids axes from being specified multiple times.
+
+ Used internally by multi-axis-checking logic.
+
+ Parameters
+ ----------
+ axis : int, iterable of int
+ The un-normalized index or indices of the axis.
+ ndim : int
+ The number of dimensions of the array that `axis` should be normalized
+ against.
+ argname : str, optional
+ A prefix to put before the error message, typically the name of the
+ argument.
+ allow_duplicate : bool, optional
+ If False, the default, disallow an axis from being specified twice.
+
+ Returns
+ -------
+ normalized_axes : tuple of int
+ The normalized axis index, such that `0 <= normalized_axis < ndim`
+
+ Raises
+ ------
+ AxisError
+ If any axis provided is out of range
+ ValueError
+ If an axis is repeated
+
+ See also
+ --------
+ normalize_axis_index : normalizing a single scalar axis
+ """
+ # Optimization to speed-up the most common cases.
+ if type(axis) not in (tuple, list):
+ try:
+ axis = [operator.index(axis)]
+ except TypeError:
+ pass
+ # Going via an iterator directly is slower than via list comprehension.
+ axis = tuple([normalize_axis_index(ax, ndim, argname) for ax in axis])
+ if not allow_duplicate and len(set(axis)) != len(axis):
+ if argname:
+ raise ValueError('repeated axis in `{}` argument'.format(argname))
+ else:
+ raise ValueError('repeated axis')
+ return axis
+
+
+def _moveaxis_dispatcher(a, source, destination):
+ return (a,)
+
+
+@array_function_dispatch(_moveaxis_dispatcher)
+def moveaxis(a, source, destination):
+ """
+ Move axes of an array to new positions.
+
+ Other axes remain in their original order.
+
+ Parameters
+ ----------
+ a : np.ndarray
+ The array whose axes should be reordered.
+ source : int or sequence of int
+ Original positions of the axes to move. These must be unique.
+ destination : int or sequence of int
+ Destination positions for each of the original axes. These must also be
+ unique.
+
+ Returns
+ -------
+ result : np.ndarray
+ Array with moved axes. This array is a view of the input array.
+
+ See Also
+ --------
+ transpose : Permute the dimensions of an array.
+ swapaxes : Interchange two axes of an array.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.zeros((3, 4, 5))
+ >>> np.moveaxis(x, 0, -1).shape
+ (4, 5, 3)
+ >>> np.moveaxis(x, -1, 0).shape
+ (5, 3, 4)
+
+ These all achieve the same result:
+
+ >>> np.transpose(x).shape
+ (5, 4, 3)
+ >>> np.swapaxes(x, 0, -1).shape
+ (5, 4, 3)
+ >>> np.moveaxis(x, [0, 1], [-1, -2]).shape
+ (5, 4, 3)
+ >>> np.moveaxis(x, [0, 1, 2], [-1, -2, -3]).shape
+ (5, 4, 3)
+
+ """
+ try:
+ # allow duck-array types if they define transpose
+ transpose = a.transpose
+ except AttributeError:
+ a = asarray(a)
+ transpose = a.transpose
+
+ source = normalize_axis_tuple(source, a.ndim, 'source')
+ destination = normalize_axis_tuple(destination, a.ndim, 'destination')
+ if len(source) != len(destination):
+ raise ValueError('`source` and `destination` arguments must have '
+ 'the same number of elements')
+
+ order = [n for n in range(a.ndim) if n not in source]
+
+ for dest, src in sorted(zip(destination, source)):
+ order.insert(dest, src)
+
+ result = transpose(order)
+ return result
+
+
+def _cross_dispatcher(a, b, axisa=None, axisb=None, axisc=None, axis=None):
+ return (a, b)
+
+
+@array_function_dispatch(_cross_dispatcher)
+def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None):
+ """
+ Return the cross product of two (arrays of) vectors.
+
+ The cross product of `a` and `b` in :math:`R^3` is a vector perpendicular
+ to both `a` and `b`. If `a` and `b` are arrays of vectors, the vectors
+ are defined by the last axis of `a` and `b` by default, and these axes
+ can have dimensions 2 or 3. Where the dimension of either `a` or `b` is
+ 2, the third component of the input vector is assumed to be zero and the
+ cross product calculated accordingly. In cases where both input vectors
+ have dimension 2, the z-component of the cross product is returned.
+
+ Parameters
+ ----------
+ a : array_like
+ Components of the first vector(s).
+ b : array_like
+ Components of the second vector(s).
+ axisa : int, optional
+ Axis of `a` that defines the vector(s). By default, the last axis.
+ axisb : int, optional
+ Axis of `b` that defines the vector(s). By default, the last axis.
+ axisc : int, optional
+ Axis of `c` containing the cross product vector(s). Ignored if
+ both input vectors have dimension 2, as the return is scalar.
+ By default, the last axis.
+ axis : int, optional
+ If defined, the axis of `a`, `b` and `c` that defines the vector(s)
+ and cross product(s). Overrides `axisa`, `axisb` and `axisc`.
+
+ Returns
+ -------
+ c : ndarray
+ Vector cross product(s).
+
+ Raises
+ ------
+ ValueError
+ When the dimension of the vector(s) in `a` and/or `b` does not
+ equal 2 or 3.
+
+ See Also
+ --------
+ inner : Inner product
+ outer : Outer product.
+ linalg.cross : An Array API compatible variation of ``np.cross``,
+ which accepts (arrays of) 3-element vectors only.
+ ix_ : Construct index arrays.
+
+ Notes
+ -----
+ Supports full broadcasting of the inputs.
+
+ Dimension-2 input arrays were deprecated in 2.0.0. If you do need this
+ functionality, you can use::
+
+ def cross2d(x, y):
+ return x[..., 0] * y[..., 1] - x[..., 1] * y[..., 0]
+
+ Examples
+ --------
+ Vector cross-product.
+
+ >>> import numpy as np
+ >>> x = [1, 2, 3]
+ >>> y = [4, 5, 6]
+ >>> np.cross(x, y)
+ array([-3, 6, -3])
+
+ One vector with dimension 2.
+
+ >>> x = [1, 2]
+ >>> y = [4, 5, 6]
+ >>> np.cross(x, y)
+ array([12, -6, -3])
+
+ Equivalently:
+
+ >>> x = [1, 2, 0]
+ >>> y = [4, 5, 6]
+ >>> np.cross(x, y)
+ array([12, -6, -3])
+
+ Both vectors with dimension 2.
+
+ >>> x = [1,2]
+ >>> y = [4,5]
+ >>> np.cross(x, y)
+ array(-3)
+
+ Multiple vector cross-products. Note that the direction of the cross
+ product vector is defined by the *right-hand rule*.
+
+ >>> x = np.array([[1,2,3], [4,5,6]])
+ >>> y = np.array([[4,5,6], [1,2,3]])
+ >>> np.cross(x, y)
+ array([[-3, 6, -3],
+ [ 3, -6, 3]])
+
+ The orientation of `c` can be changed using the `axisc` keyword.
+
+ >>> np.cross(x, y, axisc=0)
+ array([[-3, 3],
+ [ 6, -6],
+ [-3, 3]])
+
+ Change the vector definition of `x` and `y` using `axisa` and `axisb`.
+
+ >>> x = np.array([[1,2,3], [4,5,6], [7, 8, 9]])
+ >>> y = np.array([[7, 8, 9], [4,5,6], [1,2,3]])
+ >>> np.cross(x, y)
+ array([[ -6, 12, -6],
+ [ 0, 0, 0],
+ [ 6, -12, 6]])
+ >>> np.cross(x, y, axisa=0, axisb=0)
+ array([[-24, 48, -24],
+ [-30, 60, -30],
+ [-36, 72, -36]])
+
+ """
+ if axis is not None:
+ axisa, axisb, axisc = (axis,) * 3
+ a = asarray(a)
+ b = asarray(b)
+
+ if (a.ndim < 1) or (b.ndim < 1):
+ raise ValueError("At least one array has zero dimension")
+
+ # Check axisa and axisb are within bounds
+ axisa = normalize_axis_index(axisa, a.ndim, msg_prefix='axisa')
+ axisb = normalize_axis_index(axisb, b.ndim, msg_prefix='axisb')
+
+ # Move working axis to the end of the shape
+ a = moveaxis(a, axisa, -1)
+ b = moveaxis(b, axisb, -1)
+ msg = ("incompatible dimensions for cross product\n"
+ "(dimension must be 2 or 3)")
+ if a.shape[-1] not in (2, 3) or b.shape[-1] not in (2, 3):
+ raise ValueError(msg)
+ if a.shape[-1] == 2 or b.shape[-1] == 2:
+ # Deprecated in NumPy 2.0, 2023-09-26
+ warnings.warn(
+ "Arrays of 2-dimensional vectors are deprecated. Use arrays of "
+ "3-dimensional vectors instead. (deprecated in NumPy 2.0)",
+ DeprecationWarning, stacklevel=2
+ )
+
+ # Create the output array
+ shape = broadcast(a[..., 0], b[..., 0]).shape
+ if a.shape[-1] == 3 or b.shape[-1] == 3:
+ shape += (3,)
+ # Check axisc is within bounds
+ axisc = normalize_axis_index(axisc, len(shape), msg_prefix='axisc')
+ dtype = promote_types(a.dtype, b.dtype)
+ cp = empty(shape, dtype)
+
+ # recast arrays as dtype
+ a = a.astype(dtype)
+ b = b.astype(dtype)
+
+ # create local aliases for readability
+ a0 = a[..., 0]
+ a1 = a[..., 1]
+ if a.shape[-1] == 3:
+ a2 = a[..., 2]
+ b0 = b[..., 0]
+ b1 = b[..., 1]
+ if b.shape[-1] == 3:
+ b2 = b[..., 2]
+ if cp.ndim != 0 and cp.shape[-1] == 3:
+ cp0 = cp[..., 0]
+ cp1 = cp[..., 1]
+ cp2 = cp[..., 2]
+
+ if a.shape[-1] == 2:
+ if b.shape[-1] == 2:
+ # a0 * b1 - a1 * b0
+ multiply(a0, b1, out=cp)
+ cp -= a1 * b0
+ return cp
+ else:
+ assert b.shape[-1] == 3
+ # cp0 = a1 * b2 - 0 (a2 = 0)
+ # cp1 = 0 - a0 * b2 (a2 = 0)
+ # cp2 = a0 * b1 - a1 * b0
+ multiply(a1, b2, out=cp0)
+ multiply(a0, b2, out=cp1)
+ negative(cp1, out=cp1)
+ multiply(a0, b1, out=cp2)
+ cp2 -= a1 * b0
+ else:
+ assert a.shape[-1] == 3
+ if b.shape[-1] == 3:
+ # cp0 = a1 * b2 - a2 * b1
+ # cp1 = a2 * b0 - a0 * b2
+ # cp2 = a0 * b1 - a1 * b0
+ multiply(a1, b2, out=cp0)
+ tmp = array(a2 * b1)
+ cp0 -= tmp
+ multiply(a2, b0, out=cp1)
+ multiply(a0, b2, out=tmp)
+ cp1 -= tmp
+ multiply(a0, b1, out=cp2)
+ multiply(a1, b0, out=tmp)
+ cp2 -= tmp
+ else:
+ assert b.shape[-1] == 2
+ # cp0 = 0 - a2 * b1 (b2 = 0)
+ # cp1 = a2 * b0 - 0 (b2 = 0)
+ # cp2 = a0 * b1 - a1 * b0
+ multiply(a2, b1, out=cp0)
+ negative(cp0, out=cp0)
+ multiply(a2, b0, out=cp1)
+ multiply(a0, b1, out=cp2)
+ cp2 -= a1 * b0
+
+ return moveaxis(cp, -1, axisc)
+
+
+little_endian = (sys.byteorder == 'little')
+
+
+@set_module('numpy')
+def indices(dimensions, dtype=int, sparse=False):
+ """
+ Return an array representing the indices of a grid.
+
+ Compute an array where the subarrays contain index values 0, 1, ...
+ varying only along the corresponding axis.
+
+ Parameters
+ ----------
+ dimensions : sequence of ints
+ The shape of the grid.
+ dtype : dtype, optional
+ Data type of the result.
+ sparse : boolean, optional
+ Return a sparse representation of the grid instead of a dense
+ representation. Default is False.
+
+ Returns
+ -------
+ grid : one ndarray or tuple of ndarrays
+ If sparse is False:
+ Returns one array of grid indices,
+ ``grid.shape = (len(dimensions),) + tuple(dimensions)``.
+ If sparse is True:
+ Returns a tuple of arrays, with
+ ``grid[i].shape = (1, ..., 1, dimensions[i], 1, ..., 1)`` with
+ dimensions[i] in the ith place
+
+ See Also
+ --------
+ mgrid, ogrid, meshgrid
+
+ Notes
+ -----
+ The output shape in the dense case is obtained by prepending the number
+ of dimensions in front of the tuple of dimensions, i.e. if `dimensions`
+ is a tuple ``(r0, ..., rN-1)`` of length ``N``, the output shape is
+ ``(N, r0, ..., rN-1)``.
+
+ The subarrays ``grid[k]`` contains the N-D array of indices along the
+ ``k-th`` axis. Explicitly::
+
+ grid[k, i0, i1, ..., iN-1] = ik
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> grid = np.indices((2, 3))
+ >>> grid.shape
+ (2, 2, 3)
+ >>> grid[0] # row indices
+ array([[0, 0, 0],
+ [1, 1, 1]])
+ >>> grid[1] # column indices
+ array([[0, 1, 2],
+ [0, 1, 2]])
+
+ The indices can be used as an index into an array.
+
+ >>> x = np.arange(20).reshape(5, 4)
+ >>> row, col = np.indices((2, 3))
+ >>> x[row, col]
+ array([[0, 1, 2],
+ [4, 5, 6]])
+
+ Note that it would be more straightforward in the above example to
+ extract the required elements directly with ``x[:2, :3]``.
+
+ If sparse is set to true, the grid will be returned in a sparse
+ representation.
+
+ >>> i, j = np.indices((2, 3), sparse=True)
+ >>> i.shape
+ (2, 1)
+ >>> j.shape
+ (1, 3)
+ >>> i # row indices
+ array([[0],
+ [1]])
+ >>> j # column indices
+ array([[0, 1, 2]])
+
+ """
+ dimensions = tuple(dimensions)
+ N = len(dimensions)
+ shape = (1,)*N
+ if sparse:
+ res = tuple()
+ else:
+ res = empty((N,)+dimensions, dtype=dtype)
+ for i, dim in enumerate(dimensions):
+ idx = arange(dim, dtype=dtype).reshape(
+ shape[:i] + (dim,) + shape[i+1:]
+ )
+ if sparse:
+ res = res + (idx,)
+ else:
+ res[i] = idx
+ return res
+
+
+@finalize_array_function_like
+@set_module('numpy')
+def fromfunction(function, shape, *, dtype=float, like=None, **kwargs):
+ """
+ Construct an array by executing a function over each coordinate.
+
+ The resulting array therefore has a value ``fn(x, y, z)`` at
+ coordinate ``(x, y, z)``.
+
+ Parameters
+ ----------
+ function : callable
+ The function is called with N parameters, where N is the rank of
+ `shape`. Each parameter represents the coordinates of the array
+ varying along a specific axis. For example, if `shape`
+ were ``(2, 2)``, then the parameters would be
+ ``array([[0, 0], [1, 1]])`` and ``array([[0, 1], [0, 1]])``
+ shape : (N,) tuple of ints
+ Shape of the output array, which also determines the shape of
+ the coordinate arrays passed to `function`.
+ dtype : data-type, optional
+ Data-type of the coordinate arrays passed to `function`.
+ By default, `dtype` is float.
+ ${ARRAY_FUNCTION_LIKE}
+
+ .. versionadded:: 1.20.0
+
+ Returns
+ -------
+ fromfunction : any
+ The result of the call to `function` is passed back directly.
+ Therefore the shape of `fromfunction` is completely determined by
+ `function`. If `function` returns a scalar value, the shape of
+ `fromfunction` would not match the `shape` parameter.
+
+ See Also
+ --------
+ indices, meshgrid
+
+ Notes
+ -----
+ Keywords other than `dtype` and `like` are passed to `function`.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.fromfunction(lambda i, j: i, (2, 2), dtype=float)
+ array([[0., 0.],
+ [1., 1.]])
+
+ >>> np.fromfunction(lambda i, j: j, (2, 2), dtype=float)
+ array([[0., 1.],
+ [0., 1.]])
+
+ >>> np.fromfunction(lambda i, j: i == j, (3, 3), dtype=int)
+ array([[ True, False, False],
+ [False, True, False],
+ [False, False, True]])
+
+ >>> np.fromfunction(lambda i, j: i + j, (3, 3), dtype=int)
+ array([[0, 1, 2],
+ [1, 2, 3],
+ [2, 3, 4]])
+
+ """
+ if like is not None:
+ return _fromfunction_with_like(
+ like, function, shape, dtype=dtype, **kwargs)
+
+ args = indices(shape, dtype=dtype)
+ return function(*args, **kwargs)
+
+
+_fromfunction_with_like = array_function_dispatch()(fromfunction)
+
+
+def _frombuffer(buf, dtype, shape, order):
+ return frombuffer(buf, dtype=dtype).reshape(shape, order=order)
+
+
+@set_module('numpy')
+def isscalar(element):
+ """
+ Returns True if the type of `element` is a scalar type.
+
+ Parameters
+ ----------
+ element : any
+ Input argument, can be of any type and shape.
+
+ Returns
+ -------
+ val : bool
+ True if `element` is a scalar type, False if it is not.
+
+ See Also
+ --------
+ ndim : Get the number of dimensions of an array
+
+ Notes
+ -----
+ If you need a stricter way to identify a *numerical* scalar, use
+ ``isinstance(x, numbers.Number)``, as that returns ``False`` for most
+ non-numerical elements such as strings.
+
+ In most cases ``np.ndim(x) == 0`` should be used instead of this function,
+ as that will also return true for 0d arrays. This is how numpy overloads
+ functions in the style of the ``dx`` arguments to `gradient` and
+ the ``bins`` argument to `histogram`. Some key differences:
+
+ +------------------------------------+---------------+-------------------+
+ | x |``isscalar(x)``|``np.ndim(x) == 0``|
+ +====================================+===============+===================+
+ | PEP 3141 numeric objects | ``True`` | ``True`` |
+ | (including builtins) | | |
+ +------------------------------------+---------------+-------------------+
+ | builtin string and buffer objects | ``True`` | ``True`` |
+ +------------------------------------+---------------+-------------------+
+ | other builtin objects, like | ``False`` | ``True`` |
+ | `pathlib.Path`, `Exception`, | | |
+ | the result of `re.compile` | | |
+ +------------------------------------+---------------+-------------------+
+ | third-party objects like | ``False`` | ``True`` |
+ | `matplotlib.figure.Figure` | | |
+ +------------------------------------+---------------+-------------------+
+ | zero-dimensional numpy arrays | ``False`` | ``True`` |
+ +------------------------------------+---------------+-------------------+
+ | other numpy arrays | ``False`` | ``False`` |
+ +------------------------------------+---------------+-------------------+
+ | `list`, `tuple`, and other | ``False`` | ``False`` |
+ | sequence objects | | |
+ +------------------------------------+---------------+-------------------+
+
+ Examples
+ --------
+ >>> import numpy as np
+
+ >>> np.isscalar(3.1)
+ True
+
+ >>> np.isscalar(np.array(3.1))
+ False
+
+ >>> np.isscalar([3.1])
+ False
+
+ >>> np.isscalar(False)
+ True
+
+ >>> np.isscalar('numpy')
+ True
+
+ NumPy supports PEP 3141 numbers:
+
+ >>> from fractions import Fraction
+ >>> np.isscalar(Fraction(5, 17))
+ True
+ >>> from numbers import Number
+ >>> np.isscalar(Number())
+ True
+
+ """
+ return (isinstance(element, generic)
+ or type(element) in ScalarType
+ or isinstance(element, numbers.Number))
+
+
+@set_module('numpy')
+def binary_repr(num, width=None):
+ """
+ Return the binary representation of the input number as a string.
+
+ For negative numbers, if width is not given, a minus sign is added to the
+ front. If width is given, the two's complement of the number is
+ returned, with respect to that width.
+
+ In a two's-complement system negative numbers are represented by the two's
+ complement of the absolute value. This is the most common method of
+ representing signed integers on computers [1]_. A N-bit two's-complement
+ system can represent every integer in the range
+ :math:`-2^{N-1}` to :math:`+2^{N-1}-1`.
+
+ Parameters
+ ----------
+ num : int
+ Only an integer decimal number can be used.
+ width : int, optional
+ The length of the returned string if `num` is positive, or the length
+ of the two's complement if `num` is negative, provided that `width` is
+ at least a sufficient number of bits for `num` to be represented in
+ the designated form. If the `width` value is insufficient, an error is
+ raised.
+
+ Returns
+ -------
+ bin : str
+ Binary representation of `num` or two's complement of `num`.
+
+ See Also
+ --------
+ base_repr: Return a string representation of a number in the given base
+ system.
+ bin: Python's built-in binary representation generator of an integer.
+
+ Notes
+ -----
+ `binary_repr` is equivalent to using `base_repr` with base 2, but about 25x
+ faster.
+
+ References
+ ----------
+ .. [1] Wikipedia, "Two's complement",
+ https://en.wikipedia.org/wiki/Two's_complement
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.binary_repr(3)
+ '11'
+ >>> np.binary_repr(-3)
+ '-11'
+ >>> np.binary_repr(3, width=4)
+ '0011'
+
+ The two's complement is returned when the input number is negative and
+ width is specified:
+
+ >>> np.binary_repr(-3, width=3)
+ '101'
+ >>> np.binary_repr(-3, width=5)
+ '11101'
+
+ """
+ def err_if_insufficient(width, binwidth):
+ if width is not None and width < binwidth:
+ raise ValueError(
+ f"Insufficient bit {width=} provided for {binwidth=}"
+ )
+
+ # Ensure that num is a Python integer to avoid overflow or unwanted
+ # casts to floating point.
+ num = operator.index(num)
+
+ if num == 0:
+ return '0' * (width or 1)
+
+ elif num > 0:
+ binary = bin(num)[2:]
+ binwidth = len(binary)
+ outwidth = (binwidth if width is None
+ else builtins.max(binwidth, width))
+ err_if_insufficient(width, binwidth)
+ return binary.zfill(outwidth)
+
+ else:
+ if width is None:
+ return '-' + bin(-num)[2:]
+
+ else:
+ poswidth = len(bin(-num)[2:])
+
+ # See gh-8679: remove extra digit
+ # for numbers at boundaries.
+ if 2**(poswidth - 1) == -num:
+ poswidth -= 1
+
+ twocomp = 2**(poswidth + 1) + num
+ binary = bin(twocomp)[2:]
+ binwidth = len(binary)
+
+ outwidth = builtins.max(binwidth, width)
+ err_if_insufficient(width, binwidth)
+ return '1' * (outwidth - binwidth) + binary
+
+
+@set_module('numpy')
+def base_repr(number, base=2, padding=0):
+ """
+ Return a string representation of a number in the given base system.
+
+ Parameters
+ ----------
+ number : int
+ The value to convert. Positive and negative values are handled.
+ base : int, optional
+ Convert `number` to the `base` number system. The valid range is 2-36,
+ the default value is 2.
+ padding : int, optional
+ Number of zeros padded on the left. Default is 0 (no padding).
+
+ Returns
+ -------
+ out : str
+ String representation of `number` in `base` system.
+
+ See Also
+ --------
+ binary_repr : Faster version of `base_repr` for base 2.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.base_repr(5)
+ '101'
+ >>> np.base_repr(6, 5)
+ '11'
+ >>> np.base_repr(7, base=5, padding=3)
+ '00012'
+
+ >>> np.base_repr(10, base=16)
+ 'A'
+ >>> np.base_repr(32, base=16)
+ '20'
+
+ """
+ digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+ if base > len(digits):
+ raise ValueError("Bases greater than 36 not handled in base_repr.")
+ elif base < 2:
+ raise ValueError("Bases less than 2 not handled in base_repr.")
+
+ num = abs(int(number))
+ res = []
+ while num:
+ res.append(digits[num % base])
+ num //= base
+ if padding:
+ res.append('0' * padding)
+ if number < 0:
+ res.append('-')
+ return ''.join(reversed(res or '0'))
+
+
+# These are all essentially abbreviations
+# These might wind up in a special abbreviations module
+
+
+def _maketup(descr, val):
+ dt = dtype(descr)
+ # Place val in all scalar tuples:
+ fields = dt.fields
+ if fields is None:
+ return val
+ else:
+ res = [_maketup(fields[name][0], val) for name in dt.names]
+ return tuple(res)
+
+
+@finalize_array_function_like
+@set_module('numpy')
+def identity(n, dtype=None, *, like=None):
+ """
+ Return the identity array.
+
+ The identity array is a square array with ones on
+ the main diagonal.
+
+ Parameters
+ ----------
+ n : int
+ Number of rows (and columns) in `n` x `n` output.
+ dtype : data-type, optional
+ Data-type of the output. Defaults to ``float``.
+ ${ARRAY_FUNCTION_LIKE}
+
+ .. versionadded:: 1.20.0
+
+ Returns
+ -------
+ out : ndarray
+ `n` x `n` array with its main diagonal set to one,
+ and all other elements 0.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.identity(3)
+ array([[1., 0., 0.],
+ [0., 1., 0.],
+ [0., 0., 1.]])
+
+ """
+ if like is not None:
+ return _identity_with_like(like, n, dtype=dtype)
+
+ from numpy import eye
+ return eye(n, dtype=dtype, like=like)
+
+
+_identity_with_like = array_function_dispatch()(identity)
+
+
+def _allclose_dispatcher(a, b, rtol=None, atol=None, equal_nan=None):
+ return (a, b, rtol, atol)
+
+
+@array_function_dispatch(_allclose_dispatcher)
+def allclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False):
+ """
+ Returns True if two arrays are element-wise equal within a tolerance.
+
+ The tolerance values are positive, typically very small numbers. The
+ relative difference (`rtol` * abs(`b`)) and the absolute difference
+ `atol` are added together to compare against the absolute difference
+ between `a` and `b`.
+
+ .. warning:: The default `atol` is not appropriate for comparing numbers
+ with magnitudes much smaller than one (see Notes).
+
+ NaNs are treated as equal if they are in the same place and if
+ ``equal_nan=True``. Infs are treated as equal if they are in the same
+ place and of the same sign in both arrays.
+
+ Parameters
+ ----------
+ a, b : array_like
+ Input arrays to compare.
+ rtol : array_like
+ The relative tolerance parameter (see Notes).
+ atol : array_like
+ The absolute tolerance parameter (see Notes).
+ equal_nan : bool
+ Whether to compare NaN's as equal. If True, NaN's in `a` will be
+ considered equal to NaN's in `b` in the output array.
+
+ Returns
+ -------
+ allclose : bool
+ Returns True if the two arrays are equal within the given
+ tolerance; False otherwise.
+
+ See Also
+ --------
+ isclose, all, any, equal
+
+ Notes
+ -----
+ If the following equation is element-wise True, then allclose returns
+ True.::
+
+ absolute(a - b) <= (atol + rtol * absolute(b))
+
+ The above equation is not symmetric in `a` and `b`, so that
+ ``allclose(a, b)`` might be different from ``allclose(b, a)`` in
+ some rare cases.
+
+ The default value of `atol` is not appropriate when the reference value
+ `b` has magnitude smaller than one. For example, it is unlikely that
+ ``a = 1e-9`` and ``b = 2e-9`` should be considered "close", yet
+ ``allclose(1e-9, 2e-9)`` is ``True`` with default settings. Be sure
+ to select `atol` for the use case at hand, especially for defining the
+ threshold below which a non-zero value in `a` will be considered "close"
+ to a very small or zero value in `b`.
+
+ The comparison of `a` and `b` uses standard broadcasting, which
+ means that `a` and `b` need not have the same shape in order for
+ ``allclose(a, b)`` to evaluate to True. The same is true for
+ `equal` but not `array_equal`.
+
+ `allclose` is not defined for non-numeric data types.
+ `bool` is considered a numeric data-type for this purpose.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.allclose([1e10,1e-7], [1.00001e10,1e-8])
+ False
+
+ >>> np.allclose([1e10,1e-8], [1.00001e10,1e-9])
+ True
+
+ >>> np.allclose([1e10,1e-8], [1.0001e10,1e-9])
+ False
+
+ >>> np.allclose([1.0, np.nan], [1.0, np.nan])
+ False
+
+ >>> np.allclose([1.0, np.nan], [1.0, np.nan], equal_nan=True)
+ True
+
+
+ """
+ res = all(isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan))
+ return builtins.bool(res)
+
+
+def _isclose_dispatcher(a, b, rtol=None, atol=None, equal_nan=None):
+ return (a, b, rtol, atol)
+
+
+@array_function_dispatch(_isclose_dispatcher)
+def isclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False):
+ """
+ Returns a boolean array where two arrays are element-wise equal within a
+ tolerance.
+
+ The tolerance values are positive, typically very small numbers. The
+ relative difference (`rtol` * abs(`b`)) and the absolute difference
+ `atol` are added together to compare against the absolute difference
+ between `a` and `b`.
+
+ .. warning:: The default `atol` is not appropriate for comparing numbers
+ with magnitudes much smaller than one (see Notes).
+
+ Parameters
+ ----------
+ a, b : array_like
+ Input arrays to compare.
+ rtol : array_like
+ The relative tolerance parameter (see Notes).
+ atol : array_like
+ The absolute tolerance parameter (see Notes).
+ equal_nan : bool
+ Whether to compare NaN's as equal. If True, NaN's in `a` will be
+ considered equal to NaN's in `b` in the output array.
+
+ Returns
+ -------
+ y : array_like
+ Returns a boolean array of where `a` and `b` are equal within the
+ given tolerance. If both `a` and `b` are scalars, returns a single
+ boolean value.
+
+ See Also
+ --------
+ allclose
+ math.isclose
+
+ Notes
+ -----
+ For finite values, isclose uses the following equation to test whether
+ two floating point values are equivalent.::
+
+ absolute(a - b) <= (atol + rtol * absolute(b))
+
+ Unlike the built-in `math.isclose`, the above equation is not symmetric
+ in `a` and `b` -- it assumes `b` is the reference value -- so that
+ `isclose(a, b)` might be different from `isclose(b, a)`.
+
+ The default value of `atol` is not appropriate when the reference value
+ `b` has magnitude smaller than one. For example, it is unlikely that
+ ``a = 1e-9`` and ``b = 2e-9`` should be considered "close", yet
+ ``isclose(1e-9, 2e-9)`` is ``True`` with default settings. Be sure
+ to select `atol` for the use case at hand, especially for defining the
+ threshold below which a non-zero value in `a` will be considered "close"
+ to a very small or zero value in `b`.
+
+ `isclose` is not defined for non-numeric data types.
+ :class:`bool` is considered a numeric data-type for this purpose.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.isclose([1e10,1e-7], [1.00001e10,1e-8])
+ array([ True, False])
+
+ >>> np.isclose([1e10,1e-8], [1.00001e10,1e-9])
+ array([ True, True])
+
+ >>> np.isclose([1e10,1e-8], [1.0001e10,1e-9])
+ array([False, True])
+
+ >>> np.isclose([1.0, np.nan], [1.0, np.nan])
+ array([ True, False])
+
+ >>> np.isclose([1.0, np.nan], [1.0, np.nan], equal_nan=True)
+ array([ True, True])
+
+ >>> np.isclose([1e-8, 1e-7], [0.0, 0.0])
+ array([ True, False])
+
+ >>> np.isclose([1e-100, 1e-7], [0.0, 0.0], atol=0.0)
+ array([False, False])
+
+ >>> np.isclose([1e-10, 1e-10], [1e-20, 0.0])
+ array([ True, True])
+
+ >>> np.isclose([1e-10, 1e-10], [1e-20, 0.999999e-10], atol=0.0)
+ array([False, True])
+
+ """
+ # Turn all but python scalars into arrays.
+ x, y, atol, rtol = (
+ a if isinstance(a, (int, float, complex)) else asanyarray(a)
+ for a in (a, b, atol, rtol))
+
+ # Make sure y is an inexact type to avoid bad behavior on abs(MIN_INT).
+ # This will cause casting of x later. Also, make sure to allow subclasses
+ # (e.g., for numpy.ma).
+ # NOTE: We explicitly allow timedelta, which used to work. This could
+ # possibly be deprecated. See also gh-18286.
+ # timedelta works if `atol` is an integer or also a timedelta.
+ # Although, the default tolerances are unlikely to be useful
+ if (dtype := getattr(y, "dtype", None)) is not None and dtype.kind != "m":
+ dt = multiarray.result_type(y, 1.)
+ y = asanyarray(y, dtype=dt)
+ elif isinstance(y, int):
+ y = float(y)
+
+ with errstate(invalid='ignore'):
+ result = (less_equal(abs(x-y), atol + rtol * abs(y))
+ & isfinite(y)
+ | (x == y))
+ if equal_nan:
+ result |= isnan(x) & isnan(y)
+
+ return result[()] # Flatten 0d arrays to scalars
+
+
+def _array_equal_dispatcher(a1, a2, equal_nan=None):
+ return (a1, a2)
+
+
+_no_nan_types = {
+ # should use np.dtype.BoolDType, but as of writing
+ # that fails the reloading test.
+ type(dtype(nt.bool)),
+ type(dtype(nt.int8)),
+ type(dtype(nt.int16)),
+ type(dtype(nt.int32)),
+ type(dtype(nt.int64)),
+}
+
+
+def _dtype_cannot_hold_nan(dtype):
+ return type(dtype) in _no_nan_types
+
+
+@array_function_dispatch(_array_equal_dispatcher)
+def array_equal(a1, a2, equal_nan=False):
+ """
+ True if two arrays have the same shape and elements, False otherwise.
+
+ Parameters
+ ----------
+ a1, a2 : array_like
+ Input arrays.
+ equal_nan : bool
+ Whether to compare NaN's as equal. If the dtype of a1 and a2 is
+ complex, values will be considered equal if either the real or the
+ imaginary component of a given value is ``nan``.
+
+ Returns
+ -------
+ b : bool
+ Returns True if the arrays are equal.
+
+ See Also
+ --------
+ allclose: Returns True if two arrays are element-wise equal within a
+ tolerance.
+ array_equiv: Returns True if input arrays are shape consistent and all
+ elements equal.
+
+ Examples
+ --------
+ >>> import numpy as np
+
+ >>> np.array_equal([1, 2], [1, 2])
+ True
+
+ >>> np.array_equal(np.array([1, 2]), np.array([1, 2]))
+ True
+
+ >>> np.array_equal([1, 2], [1, 2, 3])
+ False
+
+ >>> np.array_equal([1, 2], [1, 4])
+ False
+
+ >>> a = np.array([1, np.nan])
+ >>> np.array_equal(a, a)
+ False
+
+ >>> np.array_equal(a, a, equal_nan=True)
+ True
+
+ When ``equal_nan`` is True, complex values with nan components are
+ considered equal if either the real *or* the imaginary components are nan.
+
+ >>> a = np.array([1 + 1j])
+ >>> b = a.copy()
+ >>> a.real = np.nan
+ >>> b.imag = np.nan
+ >>> np.array_equal(a, b, equal_nan=True)
+ True
+ """
+ try:
+ a1, a2 = asarray(a1), asarray(a2)
+ except Exception:
+ return False
+ if a1.shape != a2.shape:
+ return False
+ if not equal_nan:
+ return builtins.bool((asanyarray(a1 == a2)).all())
+
+ if a1 is a2:
+ # nan will compare equal so an array will compare equal to itself.
+ return True
+
+ cannot_have_nan = (_dtype_cannot_hold_nan(a1.dtype)
+ and _dtype_cannot_hold_nan(a2.dtype))
+ if cannot_have_nan:
+ return builtins.bool(asarray(a1 == a2).all())
+
+ # Handling NaN values if equal_nan is True
+ a1nan, a2nan = isnan(a1), isnan(a2)
+ # NaN's occur at different locations
+ if not (a1nan == a2nan).all():
+ return False
+ # Shapes of a1, a2 and masks are guaranteed to be consistent by this point
+ return builtins.bool((a1[~a1nan] == a2[~a1nan]).all())
+
+
+def _array_equiv_dispatcher(a1, a2):
+ return (a1, a2)
+
+
+@array_function_dispatch(_array_equiv_dispatcher)
+def array_equiv(a1, a2):
+ """
+ Returns True if input arrays are shape consistent and all elements equal.
+
+ Shape consistent means they are either the same shape, or one input array
+ can be broadcasted to create the same shape as the other one.
+
+ Parameters
+ ----------
+ a1, a2 : array_like
+ Input arrays.
+
+ Returns
+ -------
+ out : bool
+ True if equivalent, False otherwise.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.array_equiv([1, 2], [1, 2])
+ True
+ >>> np.array_equiv([1, 2], [1, 3])
+ False
+
+ Showing the shape equivalence:
+
+ >>> np.array_equiv([1, 2], [[1, 2], [1, 2]])
+ True
+ >>> np.array_equiv([1, 2], [[1, 2, 1, 2], [1, 2, 1, 2]])
+ False
+
+ >>> np.array_equiv([1, 2], [[1, 2], [1, 3]])
+ False
+
+ """
+ try:
+ a1, a2 = asarray(a1), asarray(a2)
+ except Exception:
+ return False
+ try:
+ multiarray.broadcast(a1, a2)
+ except Exception:
+ return False
+
+ return builtins.bool(asanyarray(a1 == a2).all())
+
+
+def _astype_dispatcher(x, dtype, /, *, copy=None, device=None):
+ return (x, dtype)
+
+
+@array_function_dispatch(_astype_dispatcher)
+def astype(x, dtype, /, *, copy=True, device=None):
+ """
+ Copies an array to a specified data type.
+
+ This function is an Array API compatible alternative to
+ `numpy.ndarray.astype`.
+
+ Parameters
+ ----------
+ x : ndarray
+ Input NumPy array to cast. ``array_likes`` are explicitly not
+ supported here.
+ dtype : dtype
+ Data type of the result.
+ copy : bool, optional
+ Specifies whether to copy an array when the specified dtype matches
+ the data type of the input array ``x``. If ``True``, a newly allocated
+ array must always be returned. If ``False`` and the specified dtype
+ matches the data type of the input array, the input array must be
+ returned; otherwise, a newly allocated array must be returned.
+ Defaults to ``True``.
+ device : str, optional
+ The device on which to place the returned array. Default: None.
+ For Array-API interoperability only, so must be ``"cpu"`` if passed.
+
+ .. versionadded:: 2.1.0
+
+ Returns
+ -------
+ out : ndarray
+ An array having the specified data type.
+
+ See Also
+ --------
+ ndarray.astype
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> arr = np.array([1, 2, 3]); arr
+ array([1, 2, 3])
+ >>> np.astype(arr, np.float64)
+ array([1., 2., 3.])
+
+ Non-copy case:
+
+ >>> arr = np.array([1, 2, 3])
+ >>> arr_noncpy = np.astype(arr, arr.dtype, copy=False)
+ >>> np.shares_memory(arr, arr_noncpy)
+ True
+
+ """
+ if not (isinstance(x, np.ndarray) or isscalar(x)):
+ raise TypeError(
+ "Input should be a NumPy array or scalar. "
+ f"It is a {type(x)} instead."
+ )
+ if device is not None and device != "cpu":
+ raise ValueError(
+ 'Device not understood. Only "cpu" is allowed, but received:'
+ f' {device}'
+ )
+ return x.astype(dtype, copy=copy)
+
+
+inf = PINF
+nan = NAN
+False_ = nt.bool(False)
+True_ = nt.bool(True)
+
+
+def extend_all(module):
+ existing = set(__all__)
+ mall = module.__all__
+ for a in mall:
+ if a not in existing:
+ __all__.append(a)
+
+
+from .umath import *
+from .numerictypes import *
+from . import fromnumeric
+from .fromnumeric import *
+from . import arrayprint
+from .arrayprint import *
+from . import _asarray
+from ._asarray import *
+from . import _ufunc_config
+from ._ufunc_config import *
+extend_all(fromnumeric)
+extend_all(umath)
+extend_all(numerictypes)
+extend_all(arrayprint)
+extend_all(_asarray)
+extend_all(_ufunc_config)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/numeric.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/numeric.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..23e8a95878bbb9b1e677bc4272f89b74e0ed490f
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/numeric.pyi
@@ -0,0 +1,896 @@
+from collections.abc import Callable, Sequence
+from typing import (
+ Any,
+ Final,
+ TypeAlias,
+ overload,
+ TypeVar,
+ Literal as L,
+ SupportsAbs,
+ SupportsIndex,
+ NoReturn,
+ TypeGuard,
+)
+from typing_extensions import Unpack
+
+import numpy as np
+from numpy import (
+ # re-exports
+ bitwise_not,
+ False_,
+ True_,
+ broadcast,
+ dtype,
+ flatiter,
+ from_dlpack,
+ inf,
+ little_endian,
+ matmul,
+ vecdot,
+ nan,
+ ndarray,
+ nditer,
+ newaxis,
+ ufunc,
+
+ # other
+ generic,
+ unsignedinteger,
+ signedinteger,
+ floating,
+ complexfloating,
+ int_,
+ intp,
+ float64,
+ timedelta64,
+ object_,
+ _AnyShapeType,
+ _OrderKACF,
+ _OrderCF,
+)
+from .fromnumeric import (
+ all as all,
+ any as any,
+ argpartition as argpartition,
+ matrix_transpose as matrix_transpose,
+ mean as mean,
+)
+from .multiarray import (
+ # re-exports
+ arange,
+ array,
+ asarray,
+ asanyarray,
+ ascontiguousarray,
+ asfortranarray,
+ can_cast,
+ concatenate,
+ copyto,
+ dot,
+ empty,
+ empty_like,
+ frombuffer,
+ fromfile,
+ fromiter,
+ fromstring,
+ inner,
+ lexsort,
+ may_share_memory,
+ min_scalar_type,
+ nested_iters,
+ putmask,
+ promote_types,
+ result_type,
+ shares_memory,
+ vdot,
+ where,
+ zeros,
+
+ # other
+ _Array,
+ _ConstructorEmpty,
+ _KwargsEmpty,
+)
+
+from numpy._typing import (
+ ArrayLike,
+ NDArray,
+ DTypeLike,
+ _SupportsDType,
+ _ShapeLike,
+ _DTypeLike,
+ _ArrayLike,
+ _SupportsArrayFunc,
+ _ScalarLike_co,
+ _ArrayLikeBool_co,
+ _ArrayLikeUInt_co,
+ _ArrayLikeInt_co,
+ _ArrayLikeFloat_co,
+ _ArrayLikeComplex_co,
+ _ArrayLikeTD64_co,
+ _ArrayLikeObject_co,
+ _ArrayLikeUnknown,
+ _NestedSequence,
+)
+
+__all__ = [
+ "newaxis",
+ "ndarray",
+ "flatiter",
+ "nditer",
+ "nested_iters",
+ "ufunc",
+ "arange",
+ "array",
+ "asarray",
+ "asanyarray",
+ "ascontiguousarray",
+ "asfortranarray",
+ "zeros",
+ "count_nonzero",
+ "empty",
+ "broadcast",
+ "dtype",
+ "fromstring",
+ "fromfile",
+ "frombuffer",
+ "from_dlpack",
+ "where",
+ "argwhere",
+ "copyto",
+ "concatenate",
+ "lexsort",
+ "astype",
+ "can_cast",
+ "promote_types",
+ "min_scalar_type",
+ "result_type",
+ "isfortran",
+ "empty_like",
+ "zeros_like",
+ "ones_like",
+ "correlate",
+ "convolve",
+ "inner",
+ "dot",
+ "outer",
+ "vdot",
+ "roll",
+ "rollaxis",
+ "moveaxis",
+ "cross",
+ "tensordot",
+ "little_endian",
+ "fromiter",
+ "array_equal",
+ "array_equiv",
+ "indices",
+ "fromfunction",
+ "isclose",
+ "isscalar",
+ "binary_repr",
+ "base_repr",
+ "ones",
+ "identity",
+ "allclose",
+ "putmask",
+ "flatnonzero",
+ "inf",
+ "nan",
+ "False_",
+ "True_",
+ "bitwise_not",
+ "full",
+ "full_like",
+ "matmul",
+ "vecdot",
+ "shares_memory",
+ "may_share_memory",
+]
+
+_T = TypeVar("_T")
+_SCT = TypeVar("_SCT", bound=generic)
+_DType = TypeVar("_DType", bound=np.dtype[Any])
+_ArrayType = TypeVar("_ArrayType", bound=np.ndarray[Any, Any])
+_ShapeType = TypeVar("_ShapeType", bound=tuple[int, ...])
+
+_CorrelateMode: TypeAlias = L["valid", "same", "full"]
+
+@overload
+def zeros_like(
+ a: _ArrayType,
+ dtype: None = ...,
+ order: _OrderKACF = ...,
+ subok: L[True] = ...,
+ shape: None = ...,
+ *,
+ device: None | L["cpu"] = ...,
+) -> _ArrayType: ...
+@overload
+def zeros_like(
+ a: _ArrayLike[_SCT],
+ dtype: None = ...,
+ order: _OrderKACF = ...,
+ subok: bool = ...,
+ shape: None | _ShapeLike = ...,
+ *,
+ device: None | L["cpu"] = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def zeros_like(
+ a: object,
+ dtype: None = ...,
+ order: _OrderKACF = ...,
+ subok: bool = ...,
+ shape: None | _ShapeLike= ...,
+ *,
+ device: None | L["cpu"] = ...,
+) -> NDArray[Any]: ...
+@overload
+def zeros_like(
+ a: Any,
+ dtype: _DTypeLike[_SCT],
+ order: _OrderKACF = ...,
+ subok: bool = ...,
+ shape: None | _ShapeLike= ...,
+ *,
+ device: None | L["cpu"] = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def zeros_like(
+ a: Any,
+ dtype: DTypeLike,
+ order: _OrderKACF = ...,
+ subok: bool = ...,
+ shape: None | _ShapeLike= ...,
+ *,
+ device: None | L["cpu"] = ...,
+) -> NDArray[Any]: ...
+
+ones: Final[_ConstructorEmpty]
+
+@overload
+def ones_like(
+ a: _ArrayType,
+ dtype: None = ...,
+ order: _OrderKACF = ...,
+ subok: L[True] = ...,
+ shape: None = ...,
+ *,
+ device: None | L["cpu"] = ...,
+) -> _ArrayType: ...
+@overload
+def ones_like(
+ a: _ArrayLike[_SCT],
+ dtype: None = ...,
+ order: _OrderKACF = ...,
+ subok: bool = ...,
+ shape: None | _ShapeLike = ...,
+ *,
+ device: None | L["cpu"] = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def ones_like(
+ a: object,
+ dtype: None = ...,
+ order: _OrderKACF = ...,
+ subok: bool = ...,
+ shape: None | _ShapeLike= ...,
+ *,
+ device: None | L["cpu"] = ...,
+) -> NDArray[Any]: ...
+@overload
+def ones_like(
+ a: Any,
+ dtype: _DTypeLike[_SCT],
+ order: _OrderKACF = ...,
+ subok: bool = ...,
+ shape: None | _ShapeLike= ...,
+ *,
+ device: None | L["cpu"] = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def ones_like(
+ a: Any,
+ dtype: DTypeLike,
+ order: _OrderKACF = ...,
+ subok: bool = ...,
+ shape: None | _ShapeLike= ...,
+ *,
+ device: None | L["cpu"] = ...,
+) -> NDArray[Any]: ...
+
+# TODO: Add overloads for bool, int, float, complex, str, bytes, and memoryview
+# 1-D shape
+@overload
+def full(
+ shape: SupportsIndex,
+ fill_value: _SCT,
+ dtype: None = ...,
+ order: _OrderCF = ...,
+ **kwargs: Unpack[_KwargsEmpty],
+) -> _Array[tuple[int], _SCT]: ...
+@overload
+def full(
+ shape: SupportsIndex,
+ fill_value: Any,
+ dtype: _DType | _SupportsDType[_DType],
+ order: _OrderCF = ...,
+ **kwargs: Unpack[_KwargsEmpty],
+) -> np.ndarray[tuple[int], _DType]: ...
+@overload
+def full(
+ shape: SupportsIndex,
+ fill_value: Any,
+ dtype: type[_SCT],
+ order: _OrderCF = ...,
+ **kwargs: Unpack[_KwargsEmpty],
+) -> _Array[tuple[int], _SCT]: ...
+@overload
+def full(
+ shape: SupportsIndex,
+ fill_value: Any,
+ dtype: None | DTypeLike = ...,
+ order: _OrderCF = ...,
+ **kwargs: Unpack[_KwargsEmpty],
+) -> _Array[tuple[int], Any]: ...
+# known shape
+@overload
+def full(
+ shape: _AnyShapeType,
+ fill_value: _SCT,
+ dtype: None = ...,
+ order: _OrderCF = ...,
+ **kwargs: Unpack[_KwargsEmpty],
+) -> _Array[_AnyShapeType, _SCT]: ...
+@overload
+def full(
+ shape: _AnyShapeType,
+ fill_value: Any,
+ dtype: _DType | _SupportsDType[_DType],
+ order: _OrderCF = ...,
+ **kwargs: Unpack[_KwargsEmpty],
+) -> np.ndarray[_AnyShapeType, _DType]: ...
+@overload
+def full(
+ shape: _AnyShapeType,
+ fill_value: Any,
+ dtype: type[_SCT],
+ order: _OrderCF = ...,
+ **kwargs: Unpack[_KwargsEmpty],
+) -> _Array[_AnyShapeType, _SCT]: ...
+@overload
+def full(
+ shape: _AnyShapeType,
+ fill_value: Any,
+ dtype: None | DTypeLike = ...,
+ order: _OrderCF = ...,
+ **kwargs: Unpack[_KwargsEmpty],
+) -> _Array[_AnyShapeType, Any]: ...
+# unknown shape
+@overload
+def full(
+ shape: _ShapeLike,
+ fill_value: _SCT,
+ dtype: None = ...,
+ order: _OrderCF = ...,
+ **kwargs: Unpack[_KwargsEmpty],
+) -> NDArray[_SCT]: ...
+@overload
+def full(
+ shape: _ShapeLike,
+ fill_value: Any,
+ dtype: _DType | _SupportsDType[_DType],
+ order: _OrderCF = ...,
+ **kwargs: Unpack[_KwargsEmpty],
+) -> np.ndarray[Any, _DType]: ...
+@overload
+def full(
+ shape: _ShapeLike,
+ fill_value: Any,
+ dtype: type[_SCT],
+ order: _OrderCF = ...,
+ **kwargs: Unpack[_KwargsEmpty],
+) -> NDArray[_SCT]: ...
+@overload
+def full(
+ shape: _ShapeLike,
+ fill_value: Any,
+ dtype: None | DTypeLike = ...,
+ order: _OrderCF = ...,
+ **kwargs: Unpack[_KwargsEmpty],
+) -> NDArray[Any]: ...
+
+@overload
+def full_like(
+ a: _ArrayType,
+ fill_value: Any,
+ dtype: None = ...,
+ order: _OrderKACF = ...,
+ subok: L[True] = ...,
+ shape: None = ...,
+ *,
+ device: None | L["cpu"] = ...,
+) -> _ArrayType: ...
+@overload
+def full_like(
+ a: _ArrayLike[_SCT],
+ fill_value: Any,
+ dtype: None = ...,
+ order: _OrderKACF = ...,
+ subok: bool = ...,
+ shape: None | _ShapeLike = ...,
+ *,
+ device: None | L["cpu"] = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def full_like(
+ a: object,
+ fill_value: Any,
+ dtype: None = ...,
+ order: _OrderKACF = ...,
+ subok: bool = ...,
+ shape: None | _ShapeLike= ...,
+ *,
+ device: None | L["cpu"] = ...,
+) -> NDArray[Any]: ...
+@overload
+def full_like(
+ a: Any,
+ fill_value: Any,
+ dtype: _DTypeLike[_SCT],
+ order: _OrderKACF = ...,
+ subok: bool = ...,
+ shape: None | _ShapeLike= ...,
+ *,
+ device: None | L["cpu"] = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def full_like(
+ a: Any,
+ fill_value: Any,
+ dtype: DTypeLike,
+ order: _OrderKACF = ...,
+ subok: bool = ...,
+ shape: None | _ShapeLike= ...,
+ *,
+ device: None | L["cpu"] = ...,
+) -> NDArray[Any]: ...
+
+#
+@overload
+def count_nonzero(a: ArrayLike, axis: None = None, *, keepdims: L[False] = False) -> int: ...
+@overload
+def count_nonzero(a: _ScalarLike_co, axis: _ShapeLike | None = None, *, keepdims: L[True]) -> np.intp: ...
+@overload
+def count_nonzero(
+ a: NDArray[Any] | _NestedSequence[ArrayLike], axis: _ShapeLike | None = None, *, keepdims: L[True]
+) -> NDArray[np.intp]: ...
+@overload
+def count_nonzero(a: ArrayLike, axis: _ShapeLike | None = None, *, keepdims: bool = False) -> Any: ...
+
+#
+def isfortran(a: NDArray[Any] | generic) -> bool: ...
+
+def argwhere(a: ArrayLike) -> NDArray[intp]: ...
+
+def flatnonzero(a: ArrayLike) -> NDArray[intp]: ...
+
+@overload
+def correlate(
+ a: _ArrayLikeUnknown,
+ v: _ArrayLikeUnknown,
+ mode: _CorrelateMode = ...,
+) -> NDArray[Any]: ...
+@overload
+def correlate(
+ a: _ArrayLikeBool_co,
+ v: _ArrayLikeBool_co,
+ mode: _CorrelateMode = ...,
+) -> NDArray[np.bool]: ...
+@overload
+def correlate(
+ a: _ArrayLikeUInt_co,
+ v: _ArrayLikeUInt_co,
+ mode: _CorrelateMode = ...,
+) -> NDArray[unsignedinteger[Any]]: ...
+@overload
+def correlate(
+ a: _ArrayLikeInt_co,
+ v: _ArrayLikeInt_co,
+ mode: _CorrelateMode = ...,
+) -> NDArray[signedinteger[Any]]: ...
+@overload
+def correlate(
+ a: _ArrayLikeFloat_co,
+ v: _ArrayLikeFloat_co,
+ mode: _CorrelateMode = ...,
+) -> NDArray[floating[Any]]: ...
+@overload
+def correlate(
+ a: _ArrayLikeComplex_co,
+ v: _ArrayLikeComplex_co,
+ mode: _CorrelateMode = ...,
+) -> NDArray[complexfloating[Any, Any]]: ...
+@overload
+def correlate(
+ a: _ArrayLikeTD64_co,
+ v: _ArrayLikeTD64_co,
+ mode: _CorrelateMode = ...,
+) -> NDArray[timedelta64]: ...
+@overload
+def correlate(
+ a: _ArrayLikeObject_co,
+ v: _ArrayLikeObject_co,
+ mode: _CorrelateMode = ...,
+) -> NDArray[object_]: ...
+
+@overload
+def convolve(
+ a: _ArrayLikeUnknown,
+ v: _ArrayLikeUnknown,
+ mode: _CorrelateMode = ...,
+) -> NDArray[Any]: ...
+@overload
+def convolve(
+ a: _ArrayLikeBool_co,
+ v: _ArrayLikeBool_co,
+ mode: _CorrelateMode = ...,
+) -> NDArray[np.bool]: ...
+@overload
+def convolve(
+ a: _ArrayLikeUInt_co,
+ v: _ArrayLikeUInt_co,
+ mode: _CorrelateMode = ...,
+) -> NDArray[unsignedinteger[Any]]: ...
+@overload
+def convolve(
+ a: _ArrayLikeInt_co,
+ v: _ArrayLikeInt_co,
+ mode: _CorrelateMode = ...,
+) -> NDArray[signedinteger[Any]]: ...
+@overload
+def convolve(
+ a: _ArrayLikeFloat_co,
+ v: _ArrayLikeFloat_co,
+ mode: _CorrelateMode = ...,
+) -> NDArray[floating[Any]]: ...
+@overload
+def convolve(
+ a: _ArrayLikeComplex_co,
+ v: _ArrayLikeComplex_co,
+ mode: _CorrelateMode = ...,
+) -> NDArray[complexfloating[Any, Any]]: ...
+@overload
+def convolve(
+ a: _ArrayLikeTD64_co,
+ v: _ArrayLikeTD64_co,
+ mode: _CorrelateMode = ...,
+) -> NDArray[timedelta64]: ...
+@overload
+def convolve(
+ a: _ArrayLikeObject_co,
+ v: _ArrayLikeObject_co,
+ mode: _CorrelateMode = ...,
+) -> NDArray[object_]: ...
+
+@overload
+def outer(
+ a: _ArrayLikeUnknown,
+ b: _ArrayLikeUnknown,
+ out: None = ...,
+) -> NDArray[Any]: ...
+@overload
+def outer(
+ a: _ArrayLikeBool_co,
+ b: _ArrayLikeBool_co,
+ out: None = ...,
+) -> NDArray[np.bool]: ...
+@overload
+def outer(
+ a: _ArrayLikeUInt_co,
+ b: _ArrayLikeUInt_co,
+ out: None = ...,
+) -> NDArray[unsignedinteger[Any]]: ...
+@overload
+def outer(
+ a: _ArrayLikeInt_co,
+ b: _ArrayLikeInt_co,
+ out: None = ...,
+) -> NDArray[signedinteger[Any]]: ...
+@overload
+def outer(
+ a: _ArrayLikeFloat_co,
+ b: _ArrayLikeFloat_co,
+ out: None = ...,
+) -> NDArray[floating[Any]]: ...
+@overload
+def outer(
+ a: _ArrayLikeComplex_co,
+ b: _ArrayLikeComplex_co,
+ out: None = ...,
+) -> NDArray[complexfloating[Any, Any]]: ...
+@overload
+def outer(
+ a: _ArrayLikeTD64_co,
+ b: _ArrayLikeTD64_co,
+ out: None = ...,
+) -> NDArray[timedelta64]: ...
+@overload
+def outer(
+ a: _ArrayLikeObject_co,
+ b: _ArrayLikeObject_co,
+ out: None = ...,
+) -> NDArray[object_]: ...
+@overload
+def outer(
+ a: _ArrayLikeComplex_co | _ArrayLikeTD64_co | _ArrayLikeObject_co,
+ b: _ArrayLikeComplex_co | _ArrayLikeTD64_co | _ArrayLikeObject_co,
+ out: _ArrayType,
+) -> _ArrayType: ...
+
+@overload
+def tensordot(
+ a: _ArrayLikeUnknown,
+ b: _ArrayLikeUnknown,
+ axes: int | tuple[_ShapeLike, _ShapeLike] = ...,
+) -> NDArray[Any]: ...
+@overload
+def tensordot(
+ a: _ArrayLikeBool_co,
+ b: _ArrayLikeBool_co,
+ axes: int | tuple[_ShapeLike, _ShapeLike] = ...,
+) -> NDArray[np.bool]: ...
+@overload
+def tensordot(
+ a: _ArrayLikeUInt_co,
+ b: _ArrayLikeUInt_co,
+ axes: int | tuple[_ShapeLike, _ShapeLike] = ...,
+) -> NDArray[unsignedinteger[Any]]: ...
+@overload
+def tensordot(
+ a: _ArrayLikeInt_co,
+ b: _ArrayLikeInt_co,
+ axes: int | tuple[_ShapeLike, _ShapeLike] = ...,
+) -> NDArray[signedinteger[Any]]: ...
+@overload
+def tensordot(
+ a: _ArrayLikeFloat_co,
+ b: _ArrayLikeFloat_co,
+ axes: int | tuple[_ShapeLike, _ShapeLike] = ...,
+) -> NDArray[floating[Any]]: ...
+@overload
+def tensordot(
+ a: _ArrayLikeComplex_co,
+ b: _ArrayLikeComplex_co,
+ axes: int | tuple[_ShapeLike, _ShapeLike] = ...,
+) -> NDArray[complexfloating[Any, Any]]: ...
+@overload
+def tensordot(
+ a: _ArrayLikeTD64_co,
+ b: _ArrayLikeTD64_co,
+ axes: int | tuple[_ShapeLike, _ShapeLike] = ...,
+) -> NDArray[timedelta64]: ...
+@overload
+def tensordot(
+ a: _ArrayLikeObject_co,
+ b: _ArrayLikeObject_co,
+ axes: int | tuple[_ShapeLike, _ShapeLike] = ...,
+) -> NDArray[object_]: ...
+
+@overload
+def roll(
+ a: _ArrayLike[_SCT],
+ shift: _ShapeLike,
+ axis: None | _ShapeLike = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def roll(
+ a: ArrayLike,
+ shift: _ShapeLike,
+ axis: None | _ShapeLike = ...,
+) -> NDArray[Any]: ...
+
+def rollaxis(
+ a: NDArray[_SCT],
+ axis: int,
+ start: int = ...,
+) -> NDArray[_SCT]: ...
+
+def moveaxis(
+ a: NDArray[_SCT],
+ source: _ShapeLike,
+ destination: _ShapeLike,
+) -> NDArray[_SCT]: ...
+
+@overload
+def cross(
+ a: _ArrayLikeUnknown,
+ b: _ArrayLikeUnknown,
+ axisa: int = ...,
+ axisb: int = ...,
+ axisc: int = ...,
+ axis: None | int = ...,
+) -> NDArray[Any]: ...
+@overload
+def cross(
+ a: _ArrayLikeBool_co,
+ b: _ArrayLikeBool_co,
+ axisa: int = ...,
+ axisb: int = ...,
+ axisc: int = ...,
+ axis: None | int = ...,
+) -> NoReturn: ...
+@overload
+def cross(
+ a: _ArrayLikeUInt_co,
+ b: _ArrayLikeUInt_co,
+ axisa: int = ...,
+ axisb: int = ...,
+ axisc: int = ...,
+ axis: None | int = ...,
+) -> NDArray[unsignedinteger[Any]]: ...
+@overload
+def cross(
+ a: _ArrayLikeInt_co,
+ b: _ArrayLikeInt_co,
+ axisa: int = ...,
+ axisb: int = ...,
+ axisc: int = ...,
+ axis: None | int = ...,
+) -> NDArray[signedinteger[Any]]: ...
+@overload
+def cross(
+ a: _ArrayLikeFloat_co,
+ b: _ArrayLikeFloat_co,
+ axisa: int = ...,
+ axisb: int = ...,
+ axisc: int = ...,
+ axis: None | int = ...,
+) -> NDArray[floating[Any]]: ...
+@overload
+def cross(
+ a: _ArrayLikeComplex_co,
+ b: _ArrayLikeComplex_co,
+ axisa: int = ...,
+ axisb: int = ...,
+ axisc: int = ...,
+ axis: None | int = ...,
+) -> NDArray[complexfloating[Any, Any]]: ...
+@overload
+def cross(
+ a: _ArrayLikeObject_co,
+ b: _ArrayLikeObject_co,
+ axisa: int = ...,
+ axisb: int = ...,
+ axisc: int = ...,
+ axis: None | int = ...,
+) -> NDArray[object_]: ...
+
+@overload
+def indices(
+ dimensions: Sequence[int],
+ dtype: type[int] = ...,
+ sparse: L[False] = ...,
+) -> NDArray[int_]: ...
+@overload
+def indices(
+ dimensions: Sequence[int],
+ dtype: type[int] = ...,
+ sparse: L[True] = ...,
+) -> tuple[NDArray[int_], ...]: ...
+@overload
+def indices(
+ dimensions: Sequence[int],
+ dtype: _DTypeLike[_SCT],
+ sparse: L[False] = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def indices(
+ dimensions: Sequence[int],
+ dtype: _DTypeLike[_SCT],
+ sparse: L[True],
+) -> tuple[NDArray[_SCT], ...]: ...
+@overload
+def indices(
+ dimensions: Sequence[int],
+ dtype: DTypeLike,
+ sparse: L[False] = ...,
+) -> NDArray[Any]: ...
+@overload
+def indices(
+ dimensions: Sequence[int],
+ dtype: DTypeLike,
+ sparse: L[True],
+) -> tuple[NDArray[Any], ...]: ...
+
+def fromfunction(
+ function: Callable[..., _T],
+ shape: Sequence[int],
+ *,
+ dtype: DTypeLike = ...,
+ like: _SupportsArrayFunc = ...,
+ **kwargs: Any,
+) -> _T: ...
+
+def isscalar(element: object) -> TypeGuard[
+ generic | bool | int | float | complex | str | bytes | memoryview
+]: ...
+
+def binary_repr(num: SupportsIndex, width: None | int = ...) -> str: ...
+
+def base_repr(
+ number: SupportsAbs[float],
+ base: float = ...,
+ padding: SupportsIndex = ...,
+) -> str: ...
+
+@overload
+def identity(
+ n: int,
+ dtype: None = ...,
+ *,
+ like: _SupportsArrayFunc = ...,
+) -> NDArray[float64]: ...
+@overload
+def identity(
+ n: int,
+ dtype: _DTypeLike[_SCT],
+ *,
+ like: _SupportsArrayFunc = ...,
+) -> NDArray[_SCT]: ...
+@overload
+def identity(
+ n: int,
+ dtype: DTypeLike,
+ *,
+ like: _SupportsArrayFunc = ...,
+) -> NDArray[Any]: ...
+
+def allclose(
+ a: ArrayLike,
+ b: ArrayLike,
+ rtol: ArrayLike = ...,
+ atol: ArrayLike = ...,
+ equal_nan: bool = ...,
+) -> bool: ...
+
+@overload
+def isclose(
+ a: _ScalarLike_co,
+ b: _ScalarLike_co,
+ rtol: ArrayLike = ...,
+ atol: ArrayLike = ...,
+ equal_nan: bool = ...,
+) -> np.bool: ...
+@overload
+def isclose(
+ a: ArrayLike,
+ b: ArrayLike,
+ rtol: ArrayLike = ...,
+ atol: ArrayLike = ...,
+ equal_nan: bool = ...,
+) -> NDArray[np.bool]: ...
+
+def array_equal(a1: ArrayLike, a2: ArrayLike, equal_nan: bool = ...) -> bool: ...
+
+def array_equiv(a1: ArrayLike, a2: ArrayLike) -> bool: ...
+
+@overload
+def astype(
+ x: ndarray[_ShapeType, dtype[Any]],
+ dtype: _DTypeLike[_SCT],
+ /,
+ *,
+ copy: bool = ...,
+ device: None | L["cpu"] = ...,
+) -> ndarray[_ShapeType, dtype[_SCT]]: ...
+@overload
+def astype(
+ x: ndarray[_ShapeType, dtype[Any]],
+ dtype: DTypeLike,
+ /,
+ *,
+ copy: bool = ...,
+ device: None | L["cpu"] = ...,
+) -> ndarray[_ShapeType, dtype[Any]]: ...
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/numerictypes.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/numerictypes.py
new file mode 100644
index 0000000000000000000000000000000000000000..70bba5b9c515d47ca771b82ae6aaedd001b1c539
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/numerictypes.py
@@ -0,0 +1,629 @@
+"""
+numerictypes: Define the numeric type objects
+
+This module is designed so "from numerictypes import \\*" is safe.
+Exported symbols include:
+
+ Dictionary with all registered number types (including aliases):
+ sctypeDict
+
+ Type objects (not all will be available, depends on platform):
+ see variable sctypes for which ones you have
+
+ Bit-width names
+
+ int8 int16 int32 int64 int128
+ uint8 uint16 uint32 uint64 uint128
+ float16 float32 float64 float96 float128 float256
+ complex32 complex64 complex128 complex192 complex256 complex512
+ datetime64 timedelta64
+
+ c-based names
+
+ bool
+
+ object_
+
+ void, str_
+
+ byte, ubyte,
+ short, ushort
+ intc, uintc,
+ intp, uintp,
+ int_, uint,
+ longlong, ulonglong,
+
+ single, csingle,
+ double, cdouble,
+ longdouble, clongdouble,
+
+ As part of the type-hierarchy: xx -- is bit-width
+
+ generic
+ +-> bool (kind=b)
+ +-> number
+ | +-> integer
+ | | +-> signedinteger (intxx) (kind=i)
+ | | | byte
+ | | | short
+ | | | intc
+ | | | intp
+ | | | int_
+ | | | longlong
+ | | \\-> unsignedinteger (uintxx) (kind=u)
+ | | ubyte
+ | | ushort
+ | | uintc
+ | | uintp
+ | | uint
+ | | ulonglong
+ | +-> inexact
+ | +-> floating (floatxx) (kind=f)
+ | | half
+ | | single
+ | | double
+ | | longdouble
+ | \\-> complexfloating (complexxx) (kind=c)
+ | csingle
+ | cdouble
+ | clongdouble
+ +-> flexible
+ | +-> character
+ | | bytes_ (kind=S)
+ | | str_ (kind=U)
+ | |
+ | \\-> void (kind=V)
+ \\-> object_ (not used much) (kind=O)
+
+"""
+import numbers
+import warnings
+
+from . import multiarray as ma
+from .multiarray import (
+ ndarray, dtype, datetime_data, datetime_as_string,
+ busday_offset, busday_count, is_busday, busdaycalendar
+ )
+from .._utils import set_module
+
+# we add more at the bottom
+__all__ = [
+ 'ScalarType', 'typecodes', 'issubdtype', 'datetime_data',
+ 'datetime_as_string', 'busday_offset', 'busday_count',
+ 'is_busday', 'busdaycalendar', 'isdtype'
+]
+
+# we don't need all these imports, but we need to keep them for compatibility
+# for users using np._core.numerictypes.UPPER_TABLE
+from ._string_helpers import ( # noqa: F401
+ english_lower, english_upper, english_capitalize, LOWER_TABLE, UPPER_TABLE
+)
+
+from ._type_aliases import (
+ sctypeDict, allTypes, sctypes
+)
+from ._dtype import _kind_name
+
+# we don't export these for import *, but we do want them accessible
+# as numerictypes.bool, etc.
+from builtins import bool, int, float, complex, object, str, bytes # noqa: F401, UP029
+
+
+# We use this later
+generic = allTypes['generic']
+
+genericTypeRank = ['bool', 'int8', 'uint8', 'int16', 'uint16',
+ 'int32', 'uint32', 'int64', 'uint64', 'int128',
+ 'uint128', 'float16',
+ 'float32', 'float64', 'float80', 'float96', 'float128',
+ 'float256',
+ 'complex32', 'complex64', 'complex128', 'complex160',
+ 'complex192', 'complex256', 'complex512', 'object']
+
+@set_module('numpy')
+def maximum_sctype(t):
+ """
+ Return the scalar type of highest precision of the same kind as the input.
+
+ .. deprecated:: 2.0
+ Use an explicit dtype like int64 or float64 instead.
+
+ Parameters
+ ----------
+ t : dtype or dtype specifier
+ The input data type. This can be a `dtype` object or an object that
+ is convertible to a `dtype`.
+
+ Returns
+ -------
+ out : dtype
+ The highest precision data type of the same kind (`dtype.kind`) as `t`.
+
+ See Also
+ --------
+ obj2sctype, mintypecode, sctype2char
+ dtype
+
+ Examples
+ --------
+ >>> from numpy._core.numerictypes import maximum_sctype
+ >>> maximum_sctype(int)
+
+ >>> maximum_sctype(np.uint8)
+
+ >>> maximum_sctype(complex)
+ # may vary
+
+ >>> maximum_sctype(str)
+
+
+ >>> maximum_sctype('i2')
+
+ >>> maximum_sctype('f4')
+ # may vary
+
+ """
+
+ # Deprecated in NumPy 2.0, 2023-07-11
+ warnings.warn(
+ "`maximum_sctype` is deprecated. Use an explicit dtype like int64 "
+ "or float64 instead. (deprecated in NumPy 2.0)",
+ DeprecationWarning,
+ stacklevel=2
+ )
+
+ g = obj2sctype(t)
+ if g is None:
+ return t
+ t = g
+ base = _kind_name(dtype(t))
+ if base in sctypes:
+ return sctypes[base][-1]
+ else:
+ return t
+
+
+@set_module('numpy')
+def issctype(rep):
+ """
+ Determines whether the given object represents a scalar data-type.
+
+ Parameters
+ ----------
+ rep : any
+ If `rep` is an instance of a scalar dtype, True is returned. If not,
+ False is returned.
+
+ Returns
+ -------
+ out : bool
+ Boolean result of check whether `rep` is a scalar dtype.
+
+ See Also
+ --------
+ issubsctype, issubdtype, obj2sctype, sctype2char
+
+ Examples
+ --------
+ >>> from numpy._core.numerictypes import issctype
+ >>> issctype(np.int32)
+ True
+ >>> issctype(list)
+ False
+ >>> issctype(1.1)
+ False
+
+ Strings are also a scalar type:
+
+ >>> issctype(np.dtype('str'))
+ True
+
+ """
+ if not isinstance(rep, (type, dtype)):
+ return False
+ try:
+ res = obj2sctype(rep)
+ if res and res != object_:
+ return True
+ else:
+ return False
+ except Exception:
+ return False
+
+
+@set_module('numpy')
+def obj2sctype(rep, default=None):
+ """
+ Return the scalar dtype or NumPy equivalent of Python type of an object.
+
+ Parameters
+ ----------
+ rep : any
+ The object of which the type is returned.
+ default : any, optional
+ If given, this is returned for objects whose types can not be
+ determined. If not given, None is returned for those objects.
+
+ Returns
+ -------
+ dtype : dtype or Python type
+ The data type of `rep`.
+
+ See Also
+ --------
+ sctype2char, issctype, issubsctype, issubdtype
+
+ Examples
+ --------
+ >>> from numpy._core.numerictypes import obj2sctype
+ >>> obj2sctype(np.int32)
+
+ >>> obj2sctype(np.array([1., 2.]))
+
+ >>> obj2sctype(np.array([1.j]))
+
+
+ >>> obj2sctype(dict)
+
+ >>> obj2sctype('string')
+
+ >>> obj2sctype(1, default=list)
+
+
+ """
+ # prevent abstract classes being upcast
+ if isinstance(rep, type) and issubclass(rep, generic):
+ return rep
+ # extract dtype from arrays
+ if isinstance(rep, ndarray):
+ return rep.dtype.type
+ # fall back on dtype to convert
+ try:
+ res = dtype(rep)
+ except Exception:
+ return default
+ else:
+ return res.type
+
+
+@set_module('numpy')
+def issubclass_(arg1, arg2):
+ """
+ Determine if a class is a subclass of a second class.
+
+ `issubclass_` is equivalent to the Python built-in ``issubclass``,
+ except that it returns False instead of raising a TypeError if one
+ of the arguments is not a class.
+
+ Parameters
+ ----------
+ arg1 : class
+ Input class. True is returned if `arg1` is a subclass of `arg2`.
+ arg2 : class or tuple of classes.
+ Input class. If a tuple of classes, True is returned if `arg1` is a
+ subclass of any of the tuple elements.
+
+ Returns
+ -------
+ out : bool
+ Whether `arg1` is a subclass of `arg2` or not.
+
+ See Also
+ --------
+ issubsctype, issubdtype, issctype
+
+ Examples
+ --------
+ >>> np.issubclass_(np.int32, int)
+ False
+ >>> np.issubclass_(np.int32, float)
+ False
+ >>> np.issubclass_(np.float64, float)
+ True
+
+ """
+ try:
+ return issubclass(arg1, arg2)
+ except TypeError:
+ return False
+
+
+@set_module('numpy')
+def issubsctype(arg1, arg2):
+ """
+ Determine if the first argument is a subclass of the second argument.
+
+ Parameters
+ ----------
+ arg1, arg2 : dtype or dtype specifier
+ Data-types.
+
+ Returns
+ -------
+ out : bool
+ The result.
+
+ See Also
+ --------
+ issctype, issubdtype, obj2sctype
+
+ Examples
+ --------
+ >>> from numpy._core import issubsctype
+ >>> issubsctype('S8', str)
+ False
+ >>> issubsctype(np.array([1]), int)
+ True
+ >>> issubsctype(np.array([1]), float)
+ False
+
+ """
+ return issubclass(obj2sctype(arg1), obj2sctype(arg2))
+
+
+class _PreprocessDTypeError(Exception):
+ pass
+
+
+def _preprocess_dtype(dtype):
+ """
+ Preprocess dtype argument by:
+ 1. fetching type from a data type
+ 2. verifying that types are built-in NumPy dtypes
+ """
+ if isinstance(dtype, ma.dtype):
+ dtype = dtype.type
+ if isinstance(dtype, ndarray) or dtype not in allTypes.values():
+ raise _PreprocessDTypeError
+ return dtype
+
+
+@set_module('numpy')
+def isdtype(dtype, kind):
+ """
+ Determine if a provided dtype is of a specified data type ``kind``.
+
+ This function only supports built-in NumPy's data types.
+ Third-party dtypes are not yet supported.
+
+ Parameters
+ ----------
+ dtype : dtype
+ The input dtype.
+ kind : dtype or str or tuple of dtypes/strs.
+ dtype or dtype kind. Allowed dtype kinds are:
+ * ``'bool'`` : boolean kind
+ * ``'signed integer'`` : signed integer data types
+ * ``'unsigned integer'`` : unsigned integer data types
+ * ``'integral'`` : integer data types
+ * ``'real floating'`` : real-valued floating-point data types
+ * ``'complex floating'`` : complex floating-point data types
+ * ``'numeric'`` : numeric data types
+
+ Returns
+ -------
+ out : bool
+
+ See Also
+ --------
+ issubdtype
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.isdtype(np.float32, np.float64)
+ False
+ >>> np.isdtype(np.float32, "real floating")
+ True
+ >>> np.isdtype(np.complex128, ("real floating", "complex floating"))
+ True
+
+ """
+ try:
+ dtype = _preprocess_dtype(dtype)
+ except _PreprocessDTypeError:
+ raise TypeError(
+ "dtype argument must be a NumPy dtype, "
+ f"but it is a {type(dtype)}."
+ ) from None
+
+ input_kinds = kind if isinstance(kind, tuple) else (kind,)
+
+ processed_kinds = set()
+
+ for kind in input_kinds:
+ if kind == "bool":
+ processed_kinds.add(allTypes["bool"])
+ elif kind == "signed integer":
+ processed_kinds.update(sctypes["int"])
+ elif kind == "unsigned integer":
+ processed_kinds.update(sctypes["uint"])
+ elif kind == "integral":
+ processed_kinds.update(sctypes["int"] + sctypes["uint"])
+ elif kind == "real floating":
+ processed_kinds.update(sctypes["float"])
+ elif kind == "complex floating":
+ processed_kinds.update(sctypes["complex"])
+ elif kind == "numeric":
+ processed_kinds.update(
+ sctypes["int"] + sctypes["uint"] +
+ sctypes["float"] + sctypes["complex"]
+ )
+ elif isinstance(kind, str):
+ raise ValueError(
+ "kind argument is a string, but"
+ f" {kind!r} is not a known kind name."
+ )
+ else:
+ try:
+ kind = _preprocess_dtype(kind)
+ except _PreprocessDTypeError:
+ raise TypeError(
+ "kind argument must be comprised of "
+ "NumPy dtypes or strings only, "
+ f"but is a {type(kind)}."
+ ) from None
+ processed_kinds.add(kind)
+
+ return dtype in processed_kinds
+
+
+@set_module('numpy')
+def issubdtype(arg1, arg2):
+ r"""
+ Returns True if first argument is a typecode lower/equal in type hierarchy.
+
+ This is like the builtin :func:`issubclass`, but for `dtype`\ s.
+
+ Parameters
+ ----------
+ arg1, arg2 : dtype_like
+ `dtype` or object coercible to one
+
+ Returns
+ -------
+ out : bool
+
+ See Also
+ --------
+ :ref:`arrays.scalars` : Overview of the numpy type hierarchy.
+
+ Examples
+ --------
+ `issubdtype` can be used to check the type of arrays:
+
+ >>> ints = np.array([1, 2, 3], dtype=np.int32)
+ >>> np.issubdtype(ints.dtype, np.integer)
+ True
+ >>> np.issubdtype(ints.dtype, np.floating)
+ False
+
+ >>> floats = np.array([1, 2, 3], dtype=np.float32)
+ >>> np.issubdtype(floats.dtype, np.integer)
+ False
+ >>> np.issubdtype(floats.dtype, np.floating)
+ True
+
+ Similar types of different sizes are not subdtypes of each other:
+
+ >>> np.issubdtype(np.float64, np.float32)
+ False
+ >>> np.issubdtype(np.float32, np.float64)
+ False
+
+ but both are subtypes of `floating`:
+
+ >>> np.issubdtype(np.float64, np.floating)
+ True
+ >>> np.issubdtype(np.float32, np.floating)
+ True
+
+ For convenience, dtype-like objects are allowed too:
+
+ >>> np.issubdtype('S1', np.bytes_)
+ True
+ >>> np.issubdtype('i4', np.signedinteger)
+ True
+
+ """
+ if not issubclass_(arg1, generic):
+ arg1 = dtype(arg1).type
+ if not issubclass_(arg2, generic):
+ arg2 = dtype(arg2).type
+
+ return issubclass(arg1, arg2)
+
+
+@set_module('numpy')
+def sctype2char(sctype):
+ """
+ Return the string representation of a scalar dtype.
+
+ Parameters
+ ----------
+ sctype : scalar dtype or object
+ If a scalar dtype, the corresponding string character is
+ returned. If an object, `sctype2char` tries to infer its scalar type
+ and then return the corresponding string character.
+
+ Returns
+ -------
+ typechar : str
+ The string character corresponding to the scalar type.
+
+ Raises
+ ------
+ ValueError
+ If `sctype` is an object for which the type can not be inferred.
+
+ See Also
+ --------
+ obj2sctype, issctype, issubsctype, mintypecode
+
+ Examples
+ --------
+ >>> from numpy._core.numerictypes import sctype2char
+ >>> for sctype in [np.int32, np.double, np.cdouble, np.bytes_, np.ndarray]:
+ ... print(sctype2char(sctype))
+ l # may vary
+ d
+ D
+ S
+ O
+
+ >>> x = np.array([1., 2-1.j])
+ >>> sctype2char(x)
+ 'D'
+ >>> sctype2char(list)
+ 'O'
+
+ """
+ sctype = obj2sctype(sctype)
+ if sctype is None:
+ raise ValueError("unrecognized type")
+ if sctype not in sctypeDict.values():
+ # for compatibility
+ raise KeyError(sctype)
+ return dtype(sctype).char
+
+
+def _scalar_type_key(typ):
+ """A ``key`` function for `sorted`."""
+ dt = dtype(typ)
+ return (dt.kind.lower(), dt.itemsize)
+
+
+ScalarType = [int, float, complex, bool, bytes, str, memoryview]
+ScalarType += sorted(set(sctypeDict.values()), key=_scalar_type_key)
+ScalarType = tuple(ScalarType)
+
+
+# Now add the types we've determined to this module
+for key in allTypes:
+ globals()[key] = allTypes[key]
+ __all__.append(key)
+
+del key
+
+typecodes = {'Character': 'c',
+ 'Integer': 'bhilqnp',
+ 'UnsignedInteger': 'BHILQNP',
+ 'Float': 'efdg',
+ 'Complex': 'FDG',
+ 'AllInteger': 'bBhHiIlLqQnNpP',
+ 'AllFloat': 'efdgFDG',
+ 'Datetime': 'Mm',
+ 'All': '?bhilqnpBHILQNPefdgFDGSUVOMm'}
+
+# backwards compatibility --- deprecated name
+# Formal deprecation: Numpy 1.20.0, 2020-10-19 (see numpy/__init__.py)
+typeDict = sctypeDict
+
+def _register_types():
+ numbers.Integral.register(integer)
+ numbers.Complex.register(inexact)
+ numbers.Real.register(floating)
+ numbers.Number.register(number)
+
+
+_register_types()
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/numerictypes.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/numerictypes.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..ace5913f0f84ddebecbec169d4585474be107bc4
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/numerictypes.pyi
@@ -0,0 +1,217 @@
+import builtins
+from typing import (
+ Any,
+ Literal as L,
+ TypedDict,
+ type_check_only,
+)
+
+import numpy as np
+from numpy import (
+ dtype,
+ generic,
+ bool,
+ bool_,
+ uint8,
+ uint16,
+ uint32,
+ uint64,
+ ubyte,
+ ushort,
+ uintc,
+ ulong,
+ ulonglong,
+ uintp,
+ uint,
+ int8,
+ int16,
+ int32,
+ int64,
+ byte,
+ short,
+ intc,
+ long,
+ longlong,
+ intp,
+ int_,
+ float16,
+ float32,
+ float64,
+ half,
+ single,
+ double,
+ longdouble,
+ complex64,
+ complex128,
+ csingle,
+ cdouble,
+ clongdouble,
+ datetime64,
+ timedelta64,
+ object_,
+ str_,
+ bytes_,
+ void,
+ unsignedinteger,
+ character,
+ inexact,
+ number,
+ integer,
+ flexible,
+ complexfloating,
+ signedinteger,
+ floating,
+)
+from ._type_aliases import sctypeDict # noqa: F401
+from .multiarray import (
+ busday_count,
+ busday_offset,
+ busdaycalendar,
+ datetime_as_string,
+ datetime_data,
+ is_busday,
+)
+
+from numpy._typing import DTypeLike
+from numpy._typing._extended_precision import (
+ uint128,
+ uint256,
+ int128,
+ int256,
+ float80,
+ float96,
+ float128,
+ float256,
+ complex160,
+ complex192,
+ complex256,
+ complex512,
+)
+
+__all__ = [
+ "ScalarType",
+ "typecodes",
+ "issubdtype",
+ "datetime_data",
+ "datetime_as_string",
+ "busday_offset",
+ "busday_count",
+ "is_busday",
+ "busdaycalendar",
+ "isdtype",
+ "generic",
+ "unsignedinteger",
+ "character",
+ "inexact",
+ "number",
+ "integer",
+ "flexible",
+ "complexfloating",
+ "signedinteger",
+ "floating",
+ "bool",
+ "float16",
+ "float32",
+ "float64",
+ "longdouble",
+ "complex64",
+ "complex128",
+ "clongdouble",
+ "bytes_",
+ "str_",
+ "void",
+ "object_",
+ "datetime64",
+ "timedelta64",
+ "int8",
+ "byte",
+ "uint8",
+ "ubyte",
+ "int16",
+ "short",
+ "uint16",
+ "ushort",
+ "int32",
+ "intc",
+ "uint32",
+ "uintc",
+ "int64",
+ "long",
+ "uint64",
+ "ulong",
+ "longlong",
+ "ulonglong",
+ "intp",
+ "uintp",
+ "double",
+ "cdouble",
+ "single",
+ "csingle",
+ "half",
+ "bool_",
+ "int_",
+ "uint",
+ "uint128",
+ "uint256",
+ "int128",
+ "int256",
+ "float80",
+ "float96",
+ "float128",
+ "float256",
+ "complex160",
+ "complex192",
+ "complex256",
+ "complex512",
+]
+
+@type_check_only
+class _TypeCodes(TypedDict):
+ Character: L['c']
+ Integer: L['bhilqnp']
+ UnsignedInteger: L['BHILQNP']
+ Float: L['efdg']
+ Complex: L['FDG']
+ AllInteger: L['bBhHiIlLqQnNpP']
+ AllFloat: L['efdgFDG']
+ Datetime: L['Mm']
+ All: L['?bhilqnpBHILQNPefdgFDGSUVOMm']
+
+def isdtype(dtype: dtype[Any] | type[Any], kind: DTypeLike | tuple[DTypeLike, ...]) -> builtins.bool: ...
+
+def issubdtype(arg1: DTypeLike, arg2: DTypeLike) -> builtins.bool: ...
+
+typecodes: _TypeCodes
+ScalarType: tuple[
+ type[int],
+ type[float],
+ type[complex],
+ type[builtins.bool],
+ type[bytes],
+ type[str],
+ type[memoryview],
+ type[np.bool],
+ type[csingle],
+ type[cdouble],
+ type[clongdouble],
+ type[half],
+ type[single],
+ type[double],
+ type[longdouble],
+ type[byte],
+ type[short],
+ type[intc],
+ type[long],
+ type[longlong],
+ type[timedelta64],
+ type[datetime64],
+ type[object_],
+ type[bytes_],
+ type[str_],
+ type[ubyte],
+ type[ushort],
+ type[uintc],
+ type[ulong],
+ type[ulonglong],
+ type[void],
+]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/overrides.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/overrides.py
new file mode 100644
index 0000000000000000000000000000000000000000..cb466408cd39a9d9b558d7da4a95849077f01832
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/overrides.py
@@ -0,0 +1,181 @@
+"""Implementation of __array_function__ overrides from NEP-18."""
+import collections
+import functools
+
+from .._utils import set_module
+from .._utils._inspect import getargspec
+from numpy._core._multiarray_umath import (
+ add_docstring, _get_implementing_args, _ArrayFunctionDispatcher)
+
+
+ARRAY_FUNCTIONS = set()
+
+array_function_like_doc = (
+ """like : array_like, optional
+ Reference object to allow the creation of arrays which are not
+ NumPy arrays. If an array-like passed in as ``like`` supports
+ the ``__array_function__`` protocol, the result will be defined
+ by it. In this case, it ensures the creation of an array object
+ compatible with that passed in via this argument."""
+)
+
+def get_array_function_like_doc(public_api, docstring_template=""):
+ ARRAY_FUNCTIONS.add(public_api)
+ docstring = public_api.__doc__ or docstring_template
+ return docstring.replace("${ARRAY_FUNCTION_LIKE}", array_function_like_doc)
+
+def finalize_array_function_like(public_api):
+ public_api.__doc__ = get_array_function_like_doc(public_api)
+ return public_api
+
+
+add_docstring(
+ _ArrayFunctionDispatcher,
+ """
+ Class to wrap functions with checks for __array_function__ overrides.
+
+ All arguments are required, and can only be passed by position.
+
+ Parameters
+ ----------
+ dispatcher : function or None
+ The dispatcher function that returns a single sequence-like object
+ of all arguments relevant. It must have the same signature (except
+ the default values) as the actual implementation.
+ If ``None``, this is a ``like=`` dispatcher and the
+ ``_ArrayFunctionDispatcher`` must be called with ``like`` as the
+ first (additional and positional) argument.
+ implementation : function
+ Function that implements the operation on NumPy arrays without
+ overrides. Arguments passed calling the ``_ArrayFunctionDispatcher``
+ will be forwarded to this (and the ``dispatcher``) as if using
+ ``*args, **kwargs``.
+
+ Attributes
+ ----------
+ _implementation : function
+ The original implementation passed in.
+ """)
+
+
+# exposed for testing purposes; used internally by _ArrayFunctionDispatcher
+add_docstring(
+ _get_implementing_args,
+ """
+ Collect arguments on which to call __array_function__.
+
+ Parameters
+ ----------
+ relevant_args : iterable of array-like
+ Iterable of possibly array-like arguments to check for
+ __array_function__ methods.
+
+ Returns
+ -------
+ Sequence of arguments with __array_function__ methods, in the order in
+ which they should be called.
+ """)
+
+
+ArgSpec = collections.namedtuple('ArgSpec', 'args varargs keywords defaults')
+
+
+def verify_matching_signatures(implementation, dispatcher):
+ """Verify that a dispatcher function has the right signature."""
+ implementation_spec = ArgSpec(*getargspec(implementation))
+ dispatcher_spec = ArgSpec(*getargspec(dispatcher))
+
+ if (implementation_spec.args != dispatcher_spec.args or
+ implementation_spec.varargs != dispatcher_spec.varargs or
+ implementation_spec.keywords != dispatcher_spec.keywords or
+ (bool(implementation_spec.defaults) !=
+ bool(dispatcher_spec.defaults)) or
+ (implementation_spec.defaults is not None and
+ len(implementation_spec.defaults) !=
+ len(dispatcher_spec.defaults))):
+ raise RuntimeError('implementation and dispatcher for %s have '
+ 'different function signatures' % implementation)
+
+ if implementation_spec.defaults is not None:
+ if dispatcher_spec.defaults != (None,) * len(dispatcher_spec.defaults):
+ raise RuntimeError('dispatcher functions can only use None for '
+ 'default argument values')
+
+
+def array_function_dispatch(dispatcher=None, module=None, verify=True,
+ docs_from_dispatcher=False):
+ """Decorator for adding dispatch with the __array_function__ protocol.
+
+ See NEP-18 for example usage.
+
+ Parameters
+ ----------
+ dispatcher : callable or None
+ Function that when called like ``dispatcher(*args, **kwargs)`` with
+ arguments from the NumPy function call returns an iterable of
+ array-like arguments to check for ``__array_function__``.
+
+ If `None`, the first argument is used as the single `like=` argument
+ and not passed on. A function implementing `like=` must call its
+ dispatcher with `like` as the first non-keyword argument.
+ module : str, optional
+ __module__ attribute to set on new function, e.g., ``module='numpy'``.
+ By default, module is copied from the decorated function.
+ verify : bool, optional
+ If True, verify the that the signature of the dispatcher and decorated
+ function signatures match exactly: all required and optional arguments
+ should appear in order with the same names, but the default values for
+ all optional arguments should be ``None``. Only disable verification
+ if the dispatcher's signature needs to deviate for some particular
+ reason, e.g., because the function has a signature like
+ ``func(*args, **kwargs)``.
+ docs_from_dispatcher : bool, optional
+ If True, copy docs from the dispatcher function onto the dispatched
+ function, rather than from the implementation. This is useful for
+ functions defined in C, which otherwise don't have docstrings.
+
+ Returns
+ -------
+ Function suitable for decorating the implementation of a NumPy function.
+
+ """
+ def decorator(implementation):
+ if verify:
+ if dispatcher is not None:
+ verify_matching_signatures(implementation, dispatcher)
+ else:
+ # Using __code__ directly similar to verify_matching_signature
+ co = implementation.__code__
+ last_arg = co.co_argcount + co.co_kwonlyargcount - 1
+ last_arg = co.co_varnames[last_arg]
+ if last_arg != "like" or co.co_kwonlyargcount == 0:
+ raise RuntimeError(
+ "__array_function__ expects `like=` to be the last "
+ "argument and a keyword-only argument. "
+ f"{implementation} does not seem to comply.")
+
+ if docs_from_dispatcher:
+ add_docstring(implementation, dispatcher.__doc__)
+
+ public_api = _ArrayFunctionDispatcher(dispatcher, implementation)
+ public_api = functools.wraps(implementation)(public_api)
+
+ if module is not None:
+ public_api.__module__ = module
+
+ ARRAY_FUNCTIONS.add(public_api)
+
+ return public_api
+
+ return decorator
+
+
+def array_function_from_dispatcher(
+ implementation, module=None, verify=True, docs_from_dispatcher=True):
+ """Like array_function_dispatcher, but with function arguments flipped."""
+
+ def decorator(dispatcher):
+ return array_function_dispatch(
+ dispatcher, module, verify=verify,
+ docs_from_dispatcher=docs_from_dispatcher)(implementation)
+ return decorator
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/overrides.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/overrides.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..9babbcc26a0b2a52a5d42fd49aacf186b5e59c57
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/overrides.pyi
@@ -0,0 +1,50 @@
+from collections.abc import Callable, Iterable
+from typing import Any, Final, NamedTuple
+
+from typing_extensions import ParamSpec, TypeVar
+
+from numpy._typing import _SupportsArrayFunc
+
+_T = TypeVar("_T")
+_Tss = ParamSpec("_Tss")
+_FuncT = TypeVar("_FuncT", bound=Callable[..., object])
+
+###
+
+ARRAY_FUNCTIONS: set[Callable[..., Any]] = ...
+array_function_like_doc: Final[str] = ...
+
+class ArgSpec(NamedTuple):
+ args: list[str]
+ varargs: str | None
+ keywords: str | None
+ defaults: tuple[Any, ...]
+
+def get_array_function_like_doc(public_api: Callable[..., Any], docstring_template: str = "") -> str: ...
+def finalize_array_function_like(public_api: _FuncT) -> _FuncT: ...
+
+#
+def verify_matching_signatures(
+ implementation: Callable[_Tss, object],
+ dispatcher: Callable[_Tss, Iterable[_SupportsArrayFunc]],
+) -> None: ...
+
+# NOTE: This actually returns a `_ArrayFunctionDispatcher` callable wrapper object, with
+# the original wrapped callable stored in the `._implementation` attribute. It checks
+# for any `__array_function__` of the values of specific arguments that the dispatcher
+# specifies. Since the dispatcher only returns an iterable of passed array-like args,
+# this overridable behaviour is impossible to annotate.
+def array_function_dispatch(
+ dispatcher: Callable[_Tss, Iterable[_SupportsArrayFunc]] | None = None,
+ module: str | None = None,
+ verify: bool = True,
+ docs_from_dispatcher: bool = False,
+) -> Callable[[_FuncT], _FuncT]: ...
+
+#
+def array_function_from_dispatcher(
+ implementation: Callable[_Tss, _T],
+ module: str | None = None,
+ verify: bool = True,
+ docs_from_dispatcher: bool = True,
+) -> Callable[[Callable[_Tss, Iterable[_SupportsArrayFunc]]], Callable[_Tss, _T]]: ...
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/printoptions.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/printoptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ac93c2290e0e37ffaee3a0dddb32a713a978881
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/printoptions.py
@@ -0,0 +1,32 @@
+"""
+Stores and defines the low-level format_options context variable.
+
+This is defined in its own file outside of the arrayprint module
+so we can import it from C while initializing the multiarray
+C module during import without introducing circular dependencies.
+"""
+
+import sys
+from contextvars import ContextVar
+
+__all__ = ["format_options"]
+
+default_format_options_dict = {
+ "edgeitems": 3, # repr N leading and trailing items of each dimension
+ "threshold": 1000, # total items > triggers array summarization
+ "floatmode": "maxprec",
+ "precision": 8, # precision of floating point representations
+ "suppress": False, # suppress printing small floating values in exp format
+ "linewidth": 75,
+ "nanstr": "nan",
+ "infstr": "inf",
+ "sign": "-",
+ "formatter": None,
+ # Internally stored as an int to simplify comparisons; converted from/to
+ # str/False on the way in/out.
+ 'legacy': sys.maxsize,
+ 'override_repr': None,
+}
+
+format_options = ContextVar(
+ "format_options", default=default_format_options_dict.copy())
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/printoptions.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/printoptions.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..bd7c7b40692d4afb0cb2ab6a8f48b0065cc9c127
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/printoptions.pyi
@@ -0,0 +1,28 @@
+from collections.abc import Callable
+from contextvars import ContextVar
+from typing import Any, Final, TypedDict
+
+from .arrayprint import _FormatDict
+
+__all__ = ["format_options"]
+
+###
+
+class _FormatOptionsDict(TypedDict):
+ edgeitems: int
+ threshold: int
+ floatmode: str
+ precision: int
+ suppress: bool
+ linewidth: int
+ nanstr: str
+ infstr: str
+ sign: str
+ formatter: _FormatDict | None
+ legacy: int
+ override_repr: Callable[[Any], str] | None
+
+###
+
+default_format_options_dict: Final[_FormatOptionsDict] = ...
+format_options: ContextVar[_FormatOptionsDict]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/records.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/records.py
new file mode 100644
index 0000000000000000000000000000000000000000..90993badc141e05e41556d2f2f0dbef7944d410d
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/records.py
@@ -0,0 +1,1091 @@
+"""
+This module contains a set of functions for record arrays.
+"""
+import os
+import warnings
+from collections import Counter
+from contextlib import nullcontext
+
+from .._utils import set_module
+from . import numeric as sb
+from . import numerictypes as nt
+from .arrayprint import _get_legacy_print_mode
+
+# All of the functions allow formats to be a dtype
+__all__ = [
+ 'record', 'recarray', 'format_parser', 'fromarrays', 'fromrecords',
+ 'fromstring', 'fromfile', 'array', 'find_duplicate',
+]
+
+
+ndarray = sb.ndarray
+
+_byteorderconv = {'b': '>',
+ 'l': '<',
+ 'n': '=',
+ 'B': '>',
+ 'L': '<',
+ 'N': '=',
+ 'S': 's',
+ 's': 's',
+ '>': '>',
+ '<': '<',
+ '=': '=',
+ '|': '|',
+ 'I': '|',
+ 'i': '|'}
+
+# formats regular expression
+# allows multidimensional spec with a tuple syntax in front
+# of the letter code '(2,3)f4' and ' ( 2 , 3 ) f4 '
+# are equally allowed
+
+numfmt = nt.sctypeDict
+
+
+@set_module('numpy.rec')
+def find_duplicate(list):
+ """Find duplication in a list, return a list of duplicated elements"""
+ return [
+ item
+ for item, counts in Counter(list).items()
+ if counts > 1
+ ]
+
+
+@set_module('numpy.rec')
+class format_parser:
+ """
+ Class to convert formats, names, titles description to a dtype.
+
+ After constructing the format_parser object, the dtype attribute is
+ the converted data-type:
+ ``dtype = format_parser(formats, names, titles).dtype``
+
+ Attributes
+ ----------
+ dtype : dtype
+ The converted data-type.
+
+ Parameters
+ ----------
+ formats : str or list of str
+ The format description, either specified as a string with
+ comma-separated format descriptions in the form ``'f8, i4, S5'``, or
+ a list of format description strings in the form
+ ``['f8', 'i4', 'S5']``.
+ names : str or list/tuple of str
+ The field names, either specified as a comma-separated string in the
+ form ``'col1, col2, col3'``, or as a list or tuple of strings in the
+ form ``['col1', 'col2', 'col3']``.
+ An empty list can be used, in that case default field names
+ ('f0', 'f1', ...) are used.
+ titles : sequence
+ Sequence of title strings. An empty list can be used to leave titles
+ out.
+ aligned : bool, optional
+ If True, align the fields by padding as the C-compiler would.
+ Default is False.
+ byteorder : str, optional
+ If specified, all the fields will be changed to the
+ provided byte-order. Otherwise, the default byte-order is
+ used. For all available string specifiers, see `dtype.newbyteorder`.
+
+ See Also
+ --------
+ numpy.dtype, numpy.typename
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.rec.format_parser(['>> np.rec.format_parser(['f8', 'i4', 'a5'], ['col1', 'col2', 'col3'],
+ ... []).dtype
+ dtype([('col1', '>> np.rec.format_parser([' len(titles):
+ self._titles += [None] * (self._nfields - len(titles))
+
+ def _createdtype(self, byteorder):
+ dtype = sb.dtype({
+ 'names': self._names,
+ 'formats': self._f_formats,
+ 'offsets': self._offsets,
+ 'titles': self._titles,
+ })
+ if byteorder is not None:
+ byteorder = _byteorderconv[byteorder[0]]
+ dtype = dtype.newbyteorder(byteorder)
+
+ self.dtype = dtype
+
+
+class record(nt.void):
+ """A data-type scalar that allows field access as attribute lookup.
+ """
+
+ # manually set name and module so that this class's type shows up
+ # as numpy.record when printed
+ __name__ = 'record'
+ __module__ = 'numpy'
+
+ def __repr__(self):
+ if _get_legacy_print_mode() <= 113:
+ return self.__str__()
+ return super().__repr__()
+
+ def __str__(self):
+ if _get_legacy_print_mode() <= 113:
+ return str(self.item())
+ return super().__str__()
+
+ def __getattribute__(self, attr):
+ if attr in ('setfield', 'getfield', 'dtype'):
+ return nt.void.__getattribute__(self, attr)
+ try:
+ return nt.void.__getattribute__(self, attr)
+ except AttributeError:
+ pass
+ fielddict = nt.void.__getattribute__(self, 'dtype').fields
+ res = fielddict.get(attr, None)
+ if res:
+ obj = self.getfield(*res[:2])
+ # if it has fields return a record,
+ # otherwise return the object
+ try:
+ dt = obj.dtype
+ except AttributeError:
+ #happens if field is Object type
+ return obj
+ if dt.names is not None:
+ return obj.view((self.__class__, obj.dtype))
+ return obj
+ else:
+ raise AttributeError("'record' object has no "
+ "attribute '%s'" % attr)
+
+ def __setattr__(self, attr, val):
+ if attr in ('setfield', 'getfield', 'dtype'):
+ raise AttributeError("Cannot set '%s' attribute" % attr)
+ fielddict = nt.void.__getattribute__(self, 'dtype').fields
+ res = fielddict.get(attr, None)
+ if res:
+ return self.setfield(val, *res[:2])
+ else:
+ if getattr(self, attr, None):
+ return nt.void.__setattr__(self, attr, val)
+ else:
+ raise AttributeError("'record' object has no "
+ "attribute '%s'" % attr)
+
+ def __getitem__(self, indx):
+ obj = nt.void.__getitem__(self, indx)
+
+ # copy behavior of record.__getattribute__,
+ if isinstance(obj, nt.void) and obj.dtype.names is not None:
+ return obj.view((self.__class__, obj.dtype))
+ else:
+ # return a single element
+ return obj
+
+ def pprint(self):
+ """Pretty-print all fields."""
+ # pretty-print all fields
+ names = self.dtype.names
+ maxlen = max(len(name) for name in names)
+ fmt = '%% %ds: %%s' % maxlen
+ rows = [fmt % (name, getattr(self, name)) for name in names]
+ return "\n".join(rows)
+
+# The recarray is almost identical to a standard array (which supports
+# named fields already) The biggest difference is that it can use
+# attribute-lookup to find the fields and it is constructed using
+# a record.
+
+# If byteorder is given it forces a particular byteorder on all
+# the fields (and any subfields)
+
+
+@set_module("numpy.rec")
+class recarray(ndarray):
+ """Construct an ndarray that allows field access using attributes.
+
+ Arrays may have a data-types containing fields, analogous
+ to columns in a spread sheet. An example is ``[(x, int), (y, float)]``,
+ where each entry in the array is a pair of ``(int, float)``. Normally,
+ these attributes are accessed using dictionary lookups such as ``arr['x']``
+ and ``arr['y']``. Record arrays allow the fields to be accessed as members
+ of the array, using ``arr.x`` and ``arr.y``.
+
+ Parameters
+ ----------
+ shape : tuple
+ Shape of output array.
+ dtype : data-type, optional
+ The desired data-type. By default, the data-type is determined
+ from `formats`, `names`, `titles`, `aligned` and `byteorder`.
+ formats : list of data-types, optional
+ A list containing the data-types for the different columns, e.g.
+ ``['i4', 'f8', 'i4']``. `formats` does *not* support the new
+ convention of using types directly, i.e. ``(int, float, int)``.
+ Note that `formats` must be a list, not a tuple.
+ Given that `formats` is somewhat limited, we recommend specifying
+ `dtype` instead.
+ names : tuple of str, optional
+ The name of each column, e.g. ``('x', 'y', 'z')``.
+ buf : buffer, optional
+ By default, a new array is created of the given shape and data-type.
+ If `buf` is specified and is an object exposing the buffer interface,
+ the array will use the memory from the existing buffer. In this case,
+ the `offset` and `strides` keywords are available.
+
+ Other Parameters
+ ----------------
+ titles : tuple of str, optional
+ Aliases for column names. For example, if `names` were
+ ``('x', 'y', 'z')`` and `titles` is
+ ``('x_coordinate', 'y_coordinate', 'z_coordinate')``, then
+ ``arr['x']`` is equivalent to both ``arr.x`` and ``arr.x_coordinate``.
+ byteorder : {'<', '>', '='}, optional
+ Byte-order for all fields.
+ aligned : bool, optional
+ Align the fields in memory as the C-compiler would.
+ strides : tuple of ints, optional
+ Buffer (`buf`) is interpreted according to these strides (strides
+ define how many bytes each array element, row, column, etc.
+ occupy in memory).
+ offset : int, optional
+ Start reading buffer (`buf`) from this offset onwards.
+ order : {'C', 'F'}, optional
+ Row-major (C-style) or column-major (Fortran-style) order.
+
+ Returns
+ -------
+ rec : recarray
+ Empty array of the given shape and type.
+
+ See Also
+ --------
+ numpy.rec.fromrecords : Construct a record array from data.
+ numpy.record : fundamental data-type for `recarray`.
+ numpy.rec.format_parser : determine data-type from formats, names, titles.
+
+ Notes
+ -----
+ This constructor can be compared to ``empty``: it creates a new record
+ array but does not fill it with data. To create a record array from data,
+ use one of the following methods:
+
+ 1. Create a standard ndarray and convert it to a record array,
+ using ``arr.view(np.recarray)``
+ 2. Use the `buf` keyword.
+ 3. Use `np.rec.fromrecords`.
+
+ Examples
+ --------
+ Create an array with two fields, ``x`` and ``y``:
+
+ >>> import numpy as np
+ >>> x = np.array([(1.0, 2), (3.0, 4)], dtype=[('x', '>> x
+ array([(1., 2), (3., 4)], dtype=[('x', '>> x['x']
+ array([1., 3.])
+
+ View the array as a record array:
+
+ >>> x = x.view(np.recarray)
+
+ >>> x.x
+ array([1., 3.])
+
+ >>> x.y
+ array([2, 4])
+
+ Create a new, empty record array:
+
+ >>> np.recarray((2,),
+ ... dtype=[('x', int), ('y', float), ('z', int)]) #doctest: +SKIP
+ rec.array([(-1073741821, 1.2249118382103472e-301, 24547520),
+ (3471280, 1.2134086255804012e-316, 0)],
+ dtype=[('x', ' 0 or self.shape == (0,):
+ lst = sb.array2string(
+ self, separator=', ', prefix=prefix, suffix=',')
+ else:
+ # show zero-length shape unless it is (0,)
+ lst = "[], shape=%s" % (repr(self.shape),)
+
+ lf = '\n'+' '*len(prefix)
+ if _get_legacy_print_mode() <= 113:
+ lf = ' ' + lf # trailing space
+ return fmt % (lst, lf, repr_dtype)
+
+ def field(self, attr, val=None):
+ if isinstance(attr, int):
+ names = ndarray.__getattribute__(self, 'dtype').names
+ attr = names[attr]
+
+ fielddict = ndarray.__getattribute__(self, 'dtype').fields
+
+ res = fielddict[attr][:2]
+
+ if val is None:
+ obj = self.getfield(*res)
+ if obj.dtype.names is not None:
+ return obj
+ return obj.view(ndarray)
+ else:
+ return self.setfield(val, *res)
+
+
+def _deprecate_shape_0_as_None(shape):
+ if shape == 0:
+ warnings.warn(
+ "Passing `shape=0` to have the shape be inferred is deprecated, "
+ "and in future will be equivalent to `shape=(0,)`. To infer "
+ "the shape and suppress this warning, pass `shape=None` instead.",
+ FutureWarning, stacklevel=3)
+ return None
+ else:
+ return shape
+
+
+@set_module("numpy.rec")
+def fromarrays(arrayList, dtype=None, shape=None, formats=None,
+ names=None, titles=None, aligned=False, byteorder=None):
+ """Create a record array from a (flat) list of arrays
+
+ Parameters
+ ----------
+ arrayList : list or tuple
+ List of array-like objects (such as lists, tuples,
+ and ndarrays).
+ dtype : data-type, optional
+ valid dtype for all arrays
+ shape : int or tuple of ints, optional
+ Shape of the resulting array. If not provided, inferred from
+ ``arrayList[0]``.
+ formats, names, titles, aligned, byteorder :
+ If `dtype` is ``None``, these arguments are passed to
+ `numpy.rec.format_parser` to construct a dtype. See that function for
+ detailed documentation.
+
+ Returns
+ -------
+ np.recarray
+ Record array consisting of given arrayList columns.
+
+ Examples
+ --------
+ >>> x1=np.array([1,2,3,4])
+ >>> x2=np.array(['a','dd','xyz','12'])
+ >>> x3=np.array([1.1,2,3,4])
+ >>> r = np.rec.fromarrays([x1,x2,x3],names='a,b,c')
+ >>> print(r[1])
+ (2, 'dd', 2.0) # may vary
+ >>> x1[1]=34
+ >>> r.a
+ array([1, 2, 3, 4])
+
+ >>> x1 = np.array([1, 2, 3, 4])
+ >>> x2 = np.array(['a', 'dd', 'xyz', '12'])
+ >>> x3 = np.array([1.1, 2, 3,4])
+ >>> r = np.rec.fromarrays(
+ ... [x1, x2, x3],
+ ... dtype=np.dtype([('a', np.int32), ('b', 'S3'), ('c', np.float32)]))
+ >>> r
+ rec.array([(1, b'a', 1.1), (2, b'dd', 2. ), (3, b'xyz', 3. ),
+ (4, b'12', 4. )],
+ dtype=[('a', ' 0:
+ shape = shape[:-nn]
+
+ _array = recarray(shape, descr)
+
+ # populate the record array (makes a copy)
+ for k, obj in enumerate(arrayList):
+ nn = descr[k].ndim
+ testshape = obj.shape[:obj.ndim - nn]
+ name = _names[k]
+ if testshape != shape:
+ raise ValueError(f'array-shape mismatch in array {k} ("{name}")')
+
+ _array[name] = obj
+
+ return _array
+
+
+@set_module("numpy.rec")
+def fromrecords(recList, dtype=None, shape=None, formats=None, names=None,
+ titles=None, aligned=False, byteorder=None):
+ """Create a recarray from a list of records in text form.
+
+ Parameters
+ ----------
+ recList : sequence
+ data in the same field may be heterogeneous - they will be promoted
+ to the highest data type.
+ dtype : data-type, optional
+ valid dtype for all arrays
+ shape : int or tuple of ints, optional
+ shape of each array.
+ formats, names, titles, aligned, byteorder :
+ If `dtype` is ``None``, these arguments are passed to
+ `numpy.format_parser` to construct a dtype. See that function for
+ detailed documentation.
+
+ If both `formats` and `dtype` are None, then this will auto-detect
+ formats. Use list of tuples rather than list of lists for faster
+ processing.
+
+ Returns
+ -------
+ np.recarray
+ record array consisting of given recList rows.
+
+ Examples
+ --------
+ >>> r=np.rec.fromrecords([(456,'dbe',1.2),(2,'de',1.3)],
+ ... names='col1,col2,col3')
+ >>> print(r[0])
+ (456, 'dbe', 1.2)
+ >>> r.col1
+ array([456, 2])
+ >>> r.col2
+ array(['dbe', 'de'], dtype='>> import pickle
+ >>> pickle.loads(pickle.dumps(r))
+ rec.array([(456, 'dbe', 1.2), ( 2, 'de', 1.3)],
+ dtype=[('col1', ' 1:
+ raise ValueError("Can only deal with 1-d array.")
+ _array = recarray(shape, descr)
+ for k in range(_array.size):
+ _array[k] = tuple(recList[k])
+ # list of lists instead of list of tuples ?
+ # 2018-02-07, 1.14.1
+ warnings.warn(
+ "fromrecords expected a list of tuples, may have received a list "
+ "of lists instead. In the future that will raise an error",
+ FutureWarning, stacklevel=2)
+ return _array
+ else:
+ if shape is not None and retval.shape != shape:
+ retval.shape = shape
+
+ res = retval.view(recarray)
+
+ return res
+
+
+@set_module("numpy.rec")
+def fromstring(datastring, dtype=None, shape=None, offset=0, formats=None,
+ names=None, titles=None, aligned=False, byteorder=None):
+ r"""Create a record array from binary data
+
+ Note that despite the name of this function it does not accept `str`
+ instances.
+
+ Parameters
+ ----------
+ datastring : bytes-like
+ Buffer of binary data
+ dtype : data-type, optional
+ Valid dtype for all arrays
+ shape : int or tuple of ints, optional
+ Shape of each array.
+ offset : int, optional
+ Position in the buffer to start reading from.
+ formats, names, titles, aligned, byteorder :
+ If `dtype` is ``None``, these arguments are passed to
+ `numpy.format_parser` to construct a dtype. See that function for
+ detailed documentation.
+
+
+ Returns
+ -------
+ np.recarray
+ Record array view into the data in datastring. This will be readonly
+ if `datastring` is readonly.
+
+ See Also
+ --------
+ numpy.frombuffer
+
+ Examples
+ --------
+ >>> a = b'\x01\x02\x03abc'
+ >>> np.rec.fromstring(a, dtype='u1,u1,u1,S3')
+ rec.array([(1, 2, 3, b'abc')],
+ dtype=[('f0', 'u1'), ('f1', 'u1'), ('f2', 'u1'), ('f3', 'S3')])
+
+ >>> grades_dtype = [('Name', (np.str_, 10)), ('Marks', np.float64),
+ ... ('GradeLevel', np.int32)]
+ >>> grades_array = np.array([('Sam', 33.3, 3), ('Mike', 44.4, 5),
+ ... ('Aadi', 66.6, 6)], dtype=grades_dtype)
+ >>> np.rec.fromstring(grades_array.tobytes(), dtype=grades_dtype)
+ rec.array([('Sam', 33.3, 3), ('Mike', 44.4, 5), ('Aadi', 66.6, 6)],
+ dtype=[('Name', '>> s = '\x01\x02\x03abc'
+ >>> np.rec.fromstring(s, dtype='u1,u1,u1,S3')
+ Traceback (most recent call last):
+ ...
+ TypeError: a bytes-like object is required, not 'str'
+ """
+
+ if dtype is None and formats is None:
+ raise TypeError("fromstring() needs a 'dtype' or 'formats' argument")
+
+ if dtype is not None:
+ descr = sb.dtype(dtype)
+ else:
+ descr = format_parser(formats, names, titles, aligned, byteorder).dtype
+
+ itemsize = descr.itemsize
+
+ # NumPy 1.19.0, 2020-01-01
+ shape = _deprecate_shape_0_as_None(shape)
+
+ if shape in (None, -1):
+ shape = (len(datastring) - offset) // itemsize
+
+ _array = recarray(shape, descr, buf=datastring, offset=offset)
+ return _array
+
+def get_remaining_size(fd):
+ pos = fd.tell()
+ try:
+ fd.seek(0, 2)
+ return fd.tell() - pos
+ finally:
+ fd.seek(pos, 0)
+
+
+@set_module("numpy.rec")
+def fromfile(fd, dtype=None, shape=None, offset=0, formats=None,
+ names=None, titles=None, aligned=False, byteorder=None):
+ """Create an array from binary file data
+
+ Parameters
+ ----------
+ fd : str or file type
+ If file is a string or a path-like object then that file is opened,
+ else it is assumed to be a file object. The file object must
+ support random access (i.e. it must have tell and seek methods).
+ dtype : data-type, optional
+ valid dtype for all arrays
+ shape : int or tuple of ints, optional
+ shape of each array.
+ offset : int, optional
+ Position in the file to start reading from.
+ formats, names, titles, aligned, byteorder :
+ If `dtype` is ``None``, these arguments are passed to
+ `numpy.format_parser` to construct a dtype. See that function for
+ detailed documentation
+
+ Returns
+ -------
+ np.recarray
+ record array consisting of data enclosed in file.
+
+ Examples
+ --------
+ >>> from tempfile import TemporaryFile
+ >>> a = np.empty(10,dtype='f8,i4,a5')
+ >>> a[5] = (0.5,10,'abcde')
+ >>>
+ >>> fd=TemporaryFile()
+ >>> a = a.view(a.dtype.newbyteorder('<'))
+ >>> a.tofile(fd)
+ >>>
+ >>> _ = fd.seek(0)
+ >>> r=np.rec.fromfile(fd, formats='f8,i4,a5', shape=10,
+ ... byteorder='<')
+ >>> print(r[5])
+ (0.5, 10, b'abcde')
+ >>> r.shape
+ (10,)
+ """
+
+ if dtype is None and formats is None:
+ raise TypeError("fromfile() needs a 'dtype' or 'formats' argument")
+
+ # NumPy 1.19.0, 2020-01-01
+ shape = _deprecate_shape_0_as_None(shape)
+
+ if shape is None:
+ shape = (-1,)
+ elif isinstance(shape, int):
+ shape = (shape,)
+
+ if hasattr(fd, 'readinto'):
+ # GH issue 2504. fd supports io.RawIOBase or io.BufferedIOBase
+ # interface. Example of fd: gzip, BytesIO, BufferedReader
+ # file already opened
+ ctx = nullcontext(fd)
+ else:
+ # open file
+ ctx = open(os.fspath(fd), 'rb')
+
+ with ctx as fd:
+ if offset > 0:
+ fd.seek(offset, 1)
+ size = get_remaining_size(fd)
+
+ if dtype is not None:
+ descr = sb.dtype(dtype)
+ else:
+ descr = format_parser(
+ formats, names, titles, aligned, byteorder
+ ).dtype
+
+ itemsize = descr.itemsize
+
+ shapeprod = sb.array(shape).prod(dtype=nt.intp)
+ shapesize = shapeprod * itemsize
+ if shapesize < 0:
+ shape = list(shape)
+ shape[shape.index(-1)] = size // -shapesize
+ shape = tuple(shape)
+ shapeprod = sb.array(shape).prod(dtype=nt.intp)
+
+ nbytes = shapeprod * itemsize
+
+ if nbytes > size:
+ raise ValueError(
+ "Not enough bytes left in file for specified "
+ "shape and type."
+ )
+
+ # create the array
+ _array = recarray(shape, descr)
+ nbytesread = fd.readinto(_array.data)
+ if nbytesread != nbytes:
+ raise OSError("Didn't read as many bytes as expected")
+
+ return _array
+
+
+@set_module("numpy.rec")
+def array(obj, dtype=None, shape=None, offset=0, strides=None, formats=None,
+ names=None, titles=None, aligned=False, byteorder=None, copy=True):
+ """
+ Construct a record array from a wide-variety of objects.
+
+ A general-purpose record array constructor that dispatches to the
+ appropriate `recarray` creation function based on the inputs (see Notes).
+
+ Parameters
+ ----------
+ obj : any
+ Input object. See Notes for details on how various input types are
+ treated.
+ dtype : data-type, optional
+ Valid dtype for array.
+ shape : int or tuple of ints, optional
+ Shape of each array.
+ offset : int, optional
+ Position in the file or buffer to start reading from.
+ strides : tuple of ints, optional
+ Buffer (`buf`) is interpreted according to these strides (strides
+ define how many bytes each array element, row, column, etc.
+ occupy in memory).
+ formats, names, titles, aligned, byteorder :
+ If `dtype` is ``None``, these arguments are passed to
+ `numpy.format_parser` to construct a dtype. See that function for
+ detailed documentation.
+ copy : bool, optional
+ Whether to copy the input object (True), or to use a reference instead.
+ This option only applies when the input is an ndarray or recarray.
+ Defaults to True.
+
+ Returns
+ -------
+ np.recarray
+ Record array created from the specified object.
+
+ Notes
+ -----
+ If `obj` is ``None``, then call the `~numpy.recarray` constructor. If
+ `obj` is a string, then call the `fromstring` constructor. If `obj` is a
+ list or a tuple, then if the first object is an `~numpy.ndarray`, call
+ `fromarrays`, otherwise call `fromrecords`. If `obj` is a
+ `~numpy.recarray`, then make a copy of the data in the recarray
+ (if ``copy=True``) and use the new formats, names, and titles. If `obj`
+ is a file, then call `fromfile`. Finally, if obj is an `ndarray`, then
+ return ``obj.view(recarray)``, making a copy of the data if ``copy=True``.
+
+ Examples
+ --------
+ >>> a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
+ >>> a
+ array([[1, 2, 3],
+ [4, 5, 6],
+ [7, 8, 9]])
+
+ >>> np.rec.array(a)
+ rec.array([[1, 2, 3],
+ [4, 5, 6],
+ [7, 8, 9]],
+ dtype=int64)
+
+ >>> b = [(1, 1), (2, 4), (3, 9)]
+ >>> c = np.rec.array(b, formats = ['i2', 'f2'], names = ('x', 'y'))
+ >>> c
+ rec.array([(1, 1.), (2, 4.), (3, 9.)],
+ dtype=[('x', '>> c.x
+ array([1, 2, 3], dtype=int16)
+
+ >>> c.y
+ array([1., 4., 9.], dtype=float16)
+
+ >>> r = np.rec.array(['abc','def'], names=['col1','col2'])
+ >>> print(r.col1)
+ abc
+
+ >>> r.col1
+ array('abc', dtype='>> r.col2
+ array('def', dtype=' object: ...
+ def tell(self, /) -> int: ...
+ def readinto(self, buffer: memoryview, /) -> int: ...
+
+###
+
+# exported in `numpy.rec`
+class record(np.void):
+ def __getattribute__(self, attr: str) -> Any: ...
+ def __setattr__(self, attr: str, val: ArrayLike) -> None: ...
+ def pprint(self) -> str: ...
+ @overload
+ def __getitem__(self, key: str | SupportsIndex) -> Any: ...
+ @overload
+ def __getitem__(self, key: list[str]) -> record: ...
+
+# exported in `numpy.rec`
+class recarray(np.ndarray[_ShapeT_co, _DTypeT_co]):
+ __name__: ClassVar[Literal["record"]] = "record"
+ __module__: Literal["numpy"] = "numpy"
+ @overload
+ def __new__(
+ subtype,
+ shape: _ShapeLike,
+ dtype: None = None,
+ buf: _SupportsBuffer | None = None,
+ offset: SupportsIndex = 0,
+ strides: _ShapeLike | None = None,
+ *,
+ formats: DTypeLike,
+ names: str | Sequence[str] | None = None,
+ titles: str | Sequence[str] | None = None,
+ byteorder: _ByteOrder | None = None,
+ aligned: bool = False,
+ order: _OrderKACF = "C",
+ ) -> _RecArray[record]: ...
+ @overload
+ def __new__(
+ subtype,
+ shape: _ShapeLike,
+ dtype: DTypeLike,
+ buf: _SupportsBuffer | None = None,
+ offset: SupportsIndex = 0,
+ strides: _ShapeLike | None = None,
+ formats: None = None,
+ names: None = None,
+ titles: None = None,
+ byteorder: None = None,
+ aligned: Literal[False] = False,
+ order: _OrderKACF = "C",
+ ) -> _RecArray[Any]: ...
+ def __array_finalize__(self, /, obj: object) -> None: ...
+ def __getattribute__(self, attr: str, /) -> Any: ...
+ def __setattr__(self, attr: str, val: ArrayLike, /) -> None: ...
+
+ #
+ @overload
+ def field(self, /, attr: int | str, val: ArrayLike) -> None: ...
+ @overload
+ def field(self, /, attr: int | str, val: None = None) -> Any: ...
+
+# exported in `numpy.rec`
+class format_parser:
+ dtype: np.dtype[np.void]
+ def __init__(
+ self,
+ /,
+ formats: DTypeLike,
+ names: str | Sequence[str] | None,
+ titles: str | Sequence[str] | None,
+ aligned: bool = False,
+ byteorder: _ByteOrder | None = None,
+ ) -> None: ...
+
+# exported in `numpy.rec`
+@overload
+def fromarrays(
+ arrayList: Iterable[ArrayLike],
+ dtype: DTypeLike | None = None,
+ shape: _ShapeLike | None = None,
+ formats: None = None,
+ names: None = None,
+ titles: None = None,
+ aligned: bool = False,
+ byteorder: None = None,
+) -> _RecArray[Any]: ...
+@overload
+def fromarrays(
+ arrayList: Iterable[ArrayLike],
+ dtype: None = None,
+ shape: _ShapeLike | None = None,
+ *,
+ formats: DTypeLike,
+ names: str | Sequence[str] | None = None,
+ titles: str | Sequence[str] | None = None,
+ aligned: bool = False,
+ byteorder: _ByteOrder | None = None,
+) -> _RecArray[record]: ...
+
+@overload
+def fromrecords(
+ recList: _ArrayLikeVoid_co | tuple[object, ...] | _NestedSequence[tuple[object, ...]],
+ dtype: DTypeLike | None = None,
+ shape: _ShapeLike | None = None,
+ formats: None = None,
+ names: None = None,
+ titles: None = None,
+ aligned: bool = False,
+ byteorder: None = None,
+) -> _RecArray[record]: ...
+@overload
+def fromrecords(
+ recList: _ArrayLikeVoid_co | tuple[object, ...] | _NestedSequence[tuple[object, ...]],
+ dtype: None = None,
+ shape: _ShapeLike | None = None,
+ *,
+ formats: DTypeLike,
+ names: str | Sequence[str] | None = None,
+ titles: str | Sequence[str] | None = None,
+ aligned: bool = False,
+ byteorder: _ByteOrder | None = None,
+) -> _RecArray[record]: ...
+
+# exported in `numpy.rec`
+@overload
+def fromstring(
+ datastring: _SupportsBuffer,
+ dtype: DTypeLike,
+ shape: _ShapeLike | None = None,
+ offset: int = 0,
+ formats: None = None,
+ names: None = None,
+ titles: None = None,
+ aligned: bool = False,
+ byteorder: None = None,
+) -> _RecArray[record]: ...
+@overload
+def fromstring(
+ datastring: _SupportsBuffer,
+ dtype: None = None,
+ shape: _ShapeLike | None = None,
+ offset: int = 0,
+ *,
+ formats: DTypeLike,
+ names: str | Sequence[str] | None = None,
+ titles: str | Sequence[str] | None = None,
+ aligned: bool = False,
+ byteorder: _ByteOrder | None = None,
+) -> _RecArray[record]: ...
+
+# exported in `numpy.rec`
+@overload
+def fromfile(
+ fd: StrOrBytesPath | _SupportsReadInto,
+ dtype: DTypeLike,
+ shape: _ShapeLike | None = None,
+ offset: int = 0,
+ formats: None = None,
+ names: None = None,
+ titles: None = None,
+ aligned: bool = False,
+ byteorder: None = None,
+) -> _RecArray[Any]: ...
+@overload
+def fromfile(
+ fd: StrOrBytesPath | _SupportsReadInto,
+ dtype: None = None,
+ shape: _ShapeLike | None = None,
+ offset: int = 0,
+ *,
+ formats: DTypeLike,
+ names: str | Sequence[str] | None = None,
+ titles: str | Sequence[str] | None = None,
+ aligned: bool = False,
+ byteorder: _ByteOrder | None = None,
+) -> _RecArray[record]: ...
+
+# exported in `numpy.rec`
+@overload
+def array(
+ obj: _SCT | NDArray[_SCT],
+ dtype: None = None,
+ shape: _ShapeLike | None = None,
+ offset: int = 0,
+ strides: tuple[int, ...] | None = None,
+ formats: None = None,
+ names: None = None,
+ titles: None = None,
+ aligned: bool = False,
+ byteorder: None = None,
+ copy: bool = True,
+) -> _RecArray[_SCT]: ...
+@overload
+def array(
+ obj: ArrayLike,
+ dtype: DTypeLike,
+ shape: _ShapeLike | None = None,
+ offset: int = 0,
+ strides: tuple[int, ...] | None = None,
+ formats: None = None,
+ names: None = None,
+ titles: None = None,
+ aligned: bool = False,
+ byteorder: None = None,
+ copy: bool = True,
+) -> _RecArray[Any]: ...
+@overload
+def array(
+ obj: ArrayLike,
+ dtype: None = None,
+ shape: _ShapeLike | None = None,
+ offset: int = 0,
+ strides: tuple[int, ...] | None = None,
+ *,
+ formats: DTypeLike,
+ names: str | Sequence[str] | None = None,
+ titles: str | Sequence[str] | None = None,
+ aligned: bool = False,
+ byteorder: _ByteOrder | None = None,
+ copy: bool = True,
+) -> _RecArray[record]: ...
+@overload
+def array(
+ obj: None,
+ dtype: DTypeLike,
+ shape: _ShapeLike,
+ offset: int = 0,
+ strides: tuple[int, ...] | None = None,
+ formats: None = None,
+ names: None = None,
+ titles: None = None,
+ aligned: bool = False,
+ byteorder: None = None,
+ copy: bool = True,
+) -> _RecArray[Any]: ...
+@overload
+def array(
+ obj: None,
+ dtype: None = None,
+ *,
+ shape: _ShapeLike,
+ offset: int = 0,
+ strides: tuple[int, ...] | None = None,
+ formats: DTypeLike,
+ names: str | Sequence[str] | None = None,
+ titles: str | Sequence[str] | None = None,
+ aligned: bool = False,
+ byteorder: _ByteOrder | None = None,
+ copy: bool = True,
+) -> _RecArray[record]: ...
+@overload
+def array(
+ obj: _SupportsReadInto,
+ dtype: DTypeLike,
+ shape: _ShapeLike | None = None,
+ offset: int = 0,
+ strides: tuple[int, ...] | None = None,
+ formats: None = None,
+ names: None = None,
+ titles: None = None,
+ aligned: bool = False,
+ byteorder: None = None,
+ copy: bool = True,
+) -> _RecArray[Any]: ...
+@overload
+def array(
+ obj: _SupportsReadInto,
+ dtype: None = None,
+ shape: _ShapeLike | None = None,
+ offset: int = 0,
+ strides: tuple[int, ...] | None = None,
+ *,
+ formats: DTypeLike,
+ names: str | Sequence[str] | None = None,
+ titles: str | Sequence[str] | None = None,
+ aligned: bool = False,
+ byteorder: _ByteOrder | None = None,
+ copy: bool = True,
+) -> _RecArray[record]: ...
+
+# exported in `numpy.rec`
+def find_duplicate(list: Iterable[_T]) -> list[_T]: ...
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/shape_base.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/shape_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc08ab4600938ee47d1d872b64997cc597196feb
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/shape_base.py
@@ -0,0 +1,1004 @@
+__all__ = ['atleast_1d', 'atleast_2d', 'atleast_3d', 'block', 'hstack',
+ 'stack', 'unstack', 'vstack']
+
+import functools
+import itertools
+import operator
+
+from . import numeric as _nx
+from . import overrides
+from .multiarray import array, asanyarray, normalize_axis_index
+from . import fromnumeric as _from_nx
+
+array_function_dispatch = functools.partial(
+ overrides.array_function_dispatch, module='numpy')
+
+
+def _atleast_1d_dispatcher(*arys):
+ return arys
+
+
+@array_function_dispatch(_atleast_1d_dispatcher)
+def atleast_1d(*arys):
+ """
+ Convert inputs to arrays with at least one dimension.
+
+ Scalar inputs are converted to 1-dimensional arrays, whilst
+ higher-dimensional inputs are preserved.
+
+ Parameters
+ ----------
+ arys1, arys2, ... : array_like
+ One or more input arrays.
+
+ Returns
+ -------
+ ret : ndarray
+ An array, or tuple of arrays, each with ``a.ndim >= 1``.
+ Copies are made only if necessary.
+
+ See Also
+ --------
+ atleast_2d, atleast_3d
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.atleast_1d(1.0)
+ array([1.])
+
+ >>> x = np.arange(9.0).reshape(3,3)
+ >>> np.atleast_1d(x)
+ array([[0., 1., 2.],
+ [3., 4., 5.],
+ [6., 7., 8.]])
+ >>> np.atleast_1d(x) is x
+ True
+
+ >>> np.atleast_1d(1, [3, 4])
+ (array([1]), array([3, 4]))
+
+ """
+ if len(arys) == 1:
+ result = asanyarray(arys[0])
+ if result.ndim == 0:
+ result = result.reshape(1)
+ return result
+ res = []
+ for ary in arys:
+ result = asanyarray(ary)
+ if result.ndim == 0:
+ result = result.reshape(1)
+ res.append(result)
+ return tuple(res)
+
+
+def _atleast_2d_dispatcher(*arys):
+ return arys
+
+
+@array_function_dispatch(_atleast_2d_dispatcher)
+def atleast_2d(*arys):
+ """
+ View inputs as arrays with at least two dimensions.
+
+ Parameters
+ ----------
+ arys1, arys2, ... : array_like
+ One or more array-like sequences. Non-array inputs are converted
+ to arrays. Arrays that already have two or more dimensions are
+ preserved.
+
+ Returns
+ -------
+ res, res2, ... : ndarray
+ An array, or tuple of arrays, each with ``a.ndim >= 2``.
+ Copies are avoided where possible, and views with two or more
+ dimensions are returned.
+
+ See Also
+ --------
+ atleast_1d, atleast_3d
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.atleast_2d(3.0)
+ array([[3.]])
+
+ >>> x = np.arange(3.0)
+ >>> np.atleast_2d(x)
+ array([[0., 1., 2.]])
+ >>> np.atleast_2d(x).base is x
+ True
+
+ >>> np.atleast_2d(1, [1, 2], [[1, 2]])
+ (array([[1]]), array([[1, 2]]), array([[1, 2]]))
+
+ """
+ res = []
+ for ary in arys:
+ ary = asanyarray(ary)
+ if ary.ndim == 0:
+ result = ary.reshape(1, 1)
+ elif ary.ndim == 1:
+ result = ary[_nx.newaxis, :]
+ else:
+ result = ary
+ res.append(result)
+ if len(res) == 1:
+ return res[0]
+ else:
+ return tuple(res)
+
+
+def _atleast_3d_dispatcher(*arys):
+ return arys
+
+
+@array_function_dispatch(_atleast_3d_dispatcher)
+def atleast_3d(*arys):
+ """
+ View inputs as arrays with at least three dimensions.
+
+ Parameters
+ ----------
+ arys1, arys2, ... : array_like
+ One or more array-like sequences. Non-array inputs are converted to
+ arrays. Arrays that already have three or more dimensions are
+ preserved.
+
+ Returns
+ -------
+ res1, res2, ... : ndarray
+ An array, or tuple of arrays, each with ``a.ndim >= 3``. Copies are
+ avoided where possible, and views with three or more dimensions are
+ returned. For example, a 1-D array of shape ``(N,)`` becomes a view
+ of shape ``(1, N, 1)``, and a 2-D array of shape ``(M, N)`` becomes a
+ view of shape ``(M, N, 1)``.
+
+ See Also
+ --------
+ atleast_1d, atleast_2d
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.atleast_3d(3.0)
+ array([[[3.]]])
+
+ >>> x = np.arange(3.0)
+ >>> np.atleast_3d(x).shape
+ (1, 3, 1)
+
+ >>> x = np.arange(12.0).reshape(4,3)
+ >>> np.atleast_3d(x).shape
+ (4, 3, 1)
+ >>> np.atleast_3d(x).base is x.base # x is a reshape, so not base itself
+ True
+
+ >>> for arr in np.atleast_3d([1, 2], [[1, 2]], [[[1, 2]]]):
+ ... print(arr, arr.shape) # doctest: +SKIP
+ ...
+ [[[1]
+ [2]]] (1, 2, 1)
+ [[[1]
+ [2]]] (1, 2, 1)
+ [[[1 2]]] (1, 1, 2)
+
+ """
+ res = []
+ for ary in arys:
+ ary = asanyarray(ary)
+ if ary.ndim == 0:
+ result = ary.reshape(1, 1, 1)
+ elif ary.ndim == 1:
+ result = ary[_nx.newaxis, :, _nx.newaxis]
+ elif ary.ndim == 2:
+ result = ary[:, :, _nx.newaxis]
+ else:
+ result = ary
+ res.append(result)
+ if len(res) == 1:
+ return res[0]
+ else:
+ return tuple(res)
+
+
+def _arrays_for_stack_dispatcher(arrays):
+ if not hasattr(arrays, "__getitem__"):
+ raise TypeError('arrays to stack must be passed as a "sequence" type '
+ 'such as list or tuple.')
+
+ return tuple(arrays)
+
+
+def _vhstack_dispatcher(tup, *, dtype=None, casting=None):
+ return _arrays_for_stack_dispatcher(tup)
+
+
+@array_function_dispatch(_vhstack_dispatcher)
+def vstack(tup, *, dtype=None, casting="same_kind"):
+ """
+ Stack arrays in sequence vertically (row wise).
+
+ This is equivalent to concatenation along the first axis after 1-D arrays
+ of shape `(N,)` have been reshaped to `(1,N)`. Rebuilds arrays divided by
+ `vsplit`.
+
+ This function makes most sense for arrays with up to 3 dimensions. For
+ instance, for pixel-data with a height (first axis), width (second axis),
+ and r/g/b channels (third axis). The functions `concatenate`, `stack` and
+ `block` provide more general stacking and concatenation operations.
+
+ Parameters
+ ----------
+ tup : sequence of ndarrays
+ The arrays must have the same shape along all but the first axis.
+ 1-D arrays must have the same length. In the case of a single
+ array_like input, it will be treated as a sequence of arrays; i.e.,
+ each element along the zeroth axis is treated as a separate array.
+
+ dtype : str or dtype
+ If provided, the destination array will have this dtype. Cannot be
+ provided together with `out`.
+
+ .. versionadded:: 1.24
+
+ casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
+ Controls what kind of data casting may occur. Defaults to 'same_kind'.
+
+ .. versionadded:: 1.24
+
+ Returns
+ -------
+ stacked : ndarray
+ The array formed by stacking the given arrays, will be at least 2-D.
+
+ See Also
+ --------
+ concatenate : Join a sequence of arrays along an existing axis.
+ stack : Join a sequence of arrays along a new axis.
+ block : Assemble an nd-array from nested lists of blocks.
+ hstack : Stack arrays in sequence horizontally (column wise).
+ dstack : Stack arrays in sequence depth wise (along third axis).
+ column_stack : Stack 1-D arrays as columns into a 2-D array.
+ vsplit : Split an array into multiple sub-arrays vertically (row-wise).
+ unstack : Split an array into a tuple of sub-arrays along an axis.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([1, 2, 3])
+ >>> b = np.array([4, 5, 6])
+ >>> np.vstack((a,b))
+ array([[1, 2, 3],
+ [4, 5, 6]])
+
+ >>> a = np.array([[1], [2], [3]])
+ >>> b = np.array([[4], [5], [6]])
+ >>> np.vstack((a,b))
+ array([[1],
+ [2],
+ [3],
+ [4],
+ [5],
+ [6]])
+
+ """
+ arrs = atleast_2d(*tup)
+ if not isinstance(arrs, tuple):
+ arrs = (arrs,)
+ return _nx.concatenate(arrs, 0, dtype=dtype, casting=casting)
+
+
+@array_function_dispatch(_vhstack_dispatcher)
+def hstack(tup, *, dtype=None, casting="same_kind"):
+ """
+ Stack arrays in sequence horizontally (column wise).
+
+ This is equivalent to concatenation along the second axis, except for 1-D
+ arrays where it concatenates along the first axis. Rebuilds arrays divided
+ by `hsplit`.
+
+ This function makes most sense for arrays with up to 3 dimensions. For
+ instance, for pixel-data with a height (first axis), width (second axis),
+ and r/g/b channels (third axis). The functions `concatenate`, `stack` and
+ `block` provide more general stacking and concatenation operations.
+
+ Parameters
+ ----------
+ tup : sequence of ndarrays
+ The arrays must have the same shape along all but the second axis,
+ except 1-D arrays which can be any length. In the case of a single
+ array_like input, it will be treated as a sequence of arrays; i.e.,
+ each element along the zeroth axis is treated as a separate array.
+
+ dtype : str or dtype
+ If provided, the destination array will have this dtype. Cannot be
+ provided together with `out`.
+
+ .. versionadded:: 1.24
+
+ casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
+ Controls what kind of data casting may occur. Defaults to 'same_kind'.
+
+ .. versionadded:: 1.24
+
+ Returns
+ -------
+ stacked : ndarray
+ The array formed by stacking the given arrays.
+
+ See Also
+ --------
+ concatenate : Join a sequence of arrays along an existing axis.
+ stack : Join a sequence of arrays along a new axis.
+ block : Assemble an nd-array from nested lists of blocks.
+ vstack : Stack arrays in sequence vertically (row wise).
+ dstack : Stack arrays in sequence depth wise (along third axis).
+ column_stack : Stack 1-D arrays as columns into a 2-D array.
+ hsplit : Split an array into multiple sub-arrays
+ horizontally (column-wise).
+ unstack : Split an array into a tuple of sub-arrays along an axis.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array((1,2,3))
+ >>> b = np.array((4,5,6))
+ >>> np.hstack((a,b))
+ array([1, 2, 3, 4, 5, 6])
+ >>> a = np.array([[1],[2],[3]])
+ >>> b = np.array([[4],[5],[6]])
+ >>> np.hstack((a,b))
+ array([[1, 4],
+ [2, 5],
+ [3, 6]])
+
+ """
+ arrs = atleast_1d(*tup)
+ if not isinstance(arrs, tuple):
+ arrs = (arrs,)
+ # As a special case, dimension 0 of 1-dimensional arrays is "horizontal"
+ if arrs and arrs[0].ndim == 1:
+ return _nx.concatenate(arrs, 0, dtype=dtype, casting=casting)
+ else:
+ return _nx.concatenate(arrs, 1, dtype=dtype, casting=casting)
+
+
+def _stack_dispatcher(arrays, axis=None, out=None, *,
+ dtype=None, casting=None):
+ arrays = _arrays_for_stack_dispatcher(arrays)
+ if out is not None:
+ # optimize for the typical case where only arrays is provided
+ arrays = list(arrays)
+ arrays.append(out)
+ return arrays
+
+
+@array_function_dispatch(_stack_dispatcher)
+def stack(arrays, axis=0, out=None, *, dtype=None, casting="same_kind"):
+ """
+ Join a sequence of arrays along a new axis.
+
+ The ``axis`` parameter specifies the index of the new axis in the
+ dimensions of the result. For example, if ``axis=0`` it will be the first
+ dimension and if ``axis=-1`` it will be the last dimension.
+
+ Parameters
+ ----------
+ arrays : sequence of ndarrays
+ Each array must have the same shape. In the case of a single ndarray
+ array_like input, it will be treated as a sequence of arrays; i.e.,
+ each element along the zeroth axis is treated as a separate array.
+
+ axis : int, optional
+ The axis in the result array along which the input arrays are stacked.
+
+ out : ndarray, optional
+ If provided, the destination to place the result. The shape must be
+ correct, matching that of what stack would have returned if no
+ out argument were specified.
+
+ dtype : str or dtype
+ If provided, the destination array will have this dtype. Cannot be
+ provided together with `out`.
+
+ .. versionadded:: 1.24
+
+ casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
+ Controls what kind of data casting may occur. Defaults to 'same_kind'.
+
+ .. versionadded:: 1.24
+
+
+ Returns
+ -------
+ stacked : ndarray
+ The stacked array has one more dimension than the input arrays.
+
+ See Also
+ --------
+ concatenate : Join a sequence of arrays along an existing axis.
+ block : Assemble an nd-array from nested lists of blocks.
+ split : Split array into a list of multiple sub-arrays of equal size.
+ unstack : Split an array into a tuple of sub-arrays along an axis.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> rng = np.random.default_rng()
+ >>> arrays = [rng.normal(size=(3,4)) for _ in range(10)]
+ >>> np.stack(arrays, axis=0).shape
+ (10, 3, 4)
+
+ >>> np.stack(arrays, axis=1).shape
+ (3, 10, 4)
+
+ >>> np.stack(arrays, axis=2).shape
+ (3, 4, 10)
+
+ >>> a = np.array([1, 2, 3])
+ >>> b = np.array([4, 5, 6])
+ >>> np.stack((a, b))
+ array([[1, 2, 3],
+ [4, 5, 6]])
+
+ >>> np.stack((a, b), axis=-1)
+ array([[1, 4],
+ [2, 5],
+ [3, 6]])
+
+ """
+ arrays = [asanyarray(arr) for arr in arrays]
+ if not arrays:
+ raise ValueError('need at least one array to stack')
+
+ shapes = {arr.shape for arr in arrays}
+ if len(shapes) != 1:
+ raise ValueError('all input arrays must have the same shape')
+
+ result_ndim = arrays[0].ndim + 1
+ axis = normalize_axis_index(axis, result_ndim)
+
+ sl = (slice(None),) * axis + (_nx.newaxis,)
+ expanded_arrays = [arr[sl] for arr in arrays]
+ return _nx.concatenate(expanded_arrays, axis=axis, out=out,
+ dtype=dtype, casting=casting)
+
+def _unstack_dispatcher(x, /, *, axis=None):
+ return (x,)
+
+@array_function_dispatch(_unstack_dispatcher)
+def unstack(x, /, *, axis=0):
+ """
+ Split an array into a sequence of arrays along the given axis.
+
+ The ``axis`` parameter specifies the dimension along which the array will
+ be split. For example, if ``axis=0`` (the default) it will be the first
+ dimension and if ``axis=-1`` it will be the last dimension.
+
+ The result is a tuple of arrays split along ``axis``.
+
+ .. versionadded:: 2.1.0
+
+ Parameters
+ ----------
+ x : ndarray
+ The array to be unstacked.
+ axis : int, optional
+ Axis along which the array will be split. Default: ``0``.
+
+ Returns
+ -------
+ unstacked : tuple of ndarrays
+ The unstacked arrays.
+
+ See Also
+ --------
+ stack : Join a sequence of arrays along a new axis.
+ concatenate : Join a sequence of arrays along an existing axis.
+ block : Assemble an nd-array from nested lists of blocks.
+ split : Split array into a list of multiple sub-arrays of equal size.
+
+ Notes
+ -----
+ ``unstack`` serves as the reverse operation of :py:func:`stack`, i.e.,
+ ``stack(unstack(x, axis=axis), axis=axis) == x``.
+
+ This function is equivalent to ``tuple(np.moveaxis(x, axis, 0))``, since
+ iterating on an array iterates along the first axis.
+
+ Examples
+ --------
+ >>> arr = np.arange(24).reshape((2, 3, 4))
+ >>> np.unstack(arr)
+ (array([[ 0, 1, 2, 3],
+ [ 4, 5, 6, 7],
+ [ 8, 9, 10, 11]]),
+ array([[12, 13, 14, 15],
+ [16, 17, 18, 19],
+ [20, 21, 22, 23]]))
+ >>> np.unstack(arr, axis=1)
+ (array([[ 0, 1, 2, 3],
+ [12, 13, 14, 15]]),
+ array([[ 4, 5, 6, 7],
+ [16, 17, 18, 19]]),
+ array([[ 8, 9, 10, 11],
+ [20, 21, 22, 23]]))
+ >>> arr2 = np.stack(np.unstack(arr, axis=1), axis=1)
+ >>> arr2.shape
+ (2, 3, 4)
+ >>> np.all(arr == arr2)
+ np.True_
+
+ """
+ if x.ndim == 0:
+ raise ValueError("Input array must be at least 1-d.")
+ return tuple(_nx.moveaxis(x, axis, 0))
+
+# Internal functions to eliminate the overhead of repeated dispatch in one of
+# the two possible paths inside np.block.
+# Use getattr to protect against __array_function__ being disabled.
+_size = getattr(_from_nx.size, '__wrapped__', _from_nx.size)
+_ndim = getattr(_from_nx.ndim, '__wrapped__', _from_nx.ndim)
+_concatenate = getattr(_from_nx.concatenate,
+ '__wrapped__', _from_nx.concatenate)
+
+
+def _block_format_index(index):
+ """
+ Convert a list of indices ``[0, 1, 2]`` into ``"arrays[0][1][2]"``.
+ """
+ idx_str = ''.join('[{}]'.format(i) for i in index if i is not None)
+ return 'arrays' + idx_str
+
+
+def _block_check_depths_match(arrays, parent_index=[]):
+ """
+ Recursive function checking that the depths of nested lists in `arrays`
+ all match. Mismatch raises a ValueError as described in the block
+ docstring below.
+
+ The entire index (rather than just the depth) needs to be calculated
+ for each innermost list, in case an error needs to be raised, so that
+ the index of the offending list can be printed as part of the error.
+
+ Parameters
+ ----------
+ arrays : nested list of arrays
+ The arrays to check
+ parent_index : list of int
+ The full index of `arrays` within the nested lists passed to
+ `_block_check_depths_match` at the top of the recursion.
+
+ Returns
+ -------
+ first_index : list of int
+ The full index of an element from the bottom of the nesting in
+ `arrays`. If any element at the bottom is an empty list, this will
+ refer to it, and the last index along the empty axis will be None.
+ max_arr_ndim : int
+ The maximum of the ndims of the arrays nested in `arrays`.
+ final_size: int
+ The number of elements in the final array. This is used the motivate
+ the choice of algorithm used using benchmarking wisdom.
+
+ """
+ if type(arrays) is tuple:
+ # not strictly necessary, but saves us from:
+ # - more than one way to do things - no point treating tuples like
+ # lists
+ # - horribly confusing behaviour that results when tuples are
+ # treated like ndarray
+ raise TypeError(
+ '{} is a tuple. '
+ 'Only lists can be used to arrange blocks, and np.block does '
+ 'not allow implicit conversion from tuple to ndarray.'.format(
+ _block_format_index(parent_index)
+ )
+ )
+ elif type(arrays) is list and len(arrays) > 0:
+ idxs_ndims = (_block_check_depths_match(arr, parent_index + [i])
+ for i, arr in enumerate(arrays))
+
+ first_index, max_arr_ndim, final_size = next(idxs_ndims)
+ for index, ndim, size in idxs_ndims:
+ final_size += size
+ if ndim > max_arr_ndim:
+ max_arr_ndim = ndim
+ if len(index) != len(first_index):
+ raise ValueError(
+ "List depths are mismatched. First element was at depth "
+ "{}, but there is an element at depth {} ({})".format(
+ len(first_index),
+ len(index),
+ _block_format_index(index)
+ )
+ )
+ # propagate our flag that indicates an empty list at the bottom
+ if index[-1] is None:
+ first_index = index
+
+ return first_index, max_arr_ndim, final_size
+ elif type(arrays) is list and len(arrays) == 0:
+ # We've 'bottomed out' on an empty list
+ return parent_index + [None], 0, 0
+ else:
+ # We've 'bottomed out' - arrays is either a scalar or an array
+ size = _size(arrays)
+ return parent_index, _ndim(arrays), size
+
+
+def _atleast_nd(a, ndim):
+ # Ensures `a` has at least `ndim` dimensions by prepending
+ # ones to `a.shape` as necessary
+ return array(a, ndmin=ndim, copy=None, subok=True)
+
+
+def _accumulate(values):
+ return list(itertools.accumulate(values))
+
+
+def _concatenate_shapes(shapes, axis):
+ """Given array shapes, return the resulting shape and slices prefixes.
+
+ These help in nested concatenation.
+
+ Returns
+ -------
+ shape: tuple of int
+ This tuple satisfies::
+
+ shape, _ = _concatenate_shapes([arr.shape for shape in arrs], axis)
+ shape == concatenate(arrs, axis).shape
+
+ slice_prefixes: tuple of (slice(start, end), )
+ For a list of arrays being concatenated, this returns the slice
+ in the larger array at axis that needs to be sliced into.
+
+ For example, the following holds::
+
+ ret = concatenate([a, b, c], axis)
+ _, (sl_a, sl_b, sl_c) = concatenate_slices([a, b, c], axis)
+
+ ret[(slice(None),) * axis + sl_a] == a
+ ret[(slice(None),) * axis + sl_b] == b
+ ret[(slice(None),) * axis + sl_c] == c
+
+ These are called slice prefixes since they are used in the recursive
+ blocking algorithm to compute the left-most slices during the
+ recursion. Therefore, they must be prepended to rest of the slice
+ that was computed deeper in the recursion.
+
+ These are returned as tuples to ensure that they can quickly be added
+ to existing slice tuple without creating a new tuple every time.
+
+ """
+ # Cache a result that will be reused.
+ shape_at_axis = [shape[axis] for shape in shapes]
+
+ # Take a shape, any shape
+ first_shape = shapes[0]
+ first_shape_pre = first_shape[:axis]
+ first_shape_post = first_shape[axis+1:]
+
+ if any(shape[:axis] != first_shape_pre or
+ shape[axis+1:] != first_shape_post for shape in shapes):
+ raise ValueError(
+ 'Mismatched array shapes in block along axis {}.'.format(axis))
+
+ shape = (first_shape_pre + (sum(shape_at_axis),) + first_shape[axis+1:])
+
+ offsets_at_axis = _accumulate(shape_at_axis)
+ slice_prefixes = [(slice(start, end),)
+ for start, end in zip([0] + offsets_at_axis,
+ offsets_at_axis)]
+ return shape, slice_prefixes
+
+
+def _block_info_recursion(arrays, max_depth, result_ndim, depth=0):
+ """
+ Returns the shape of the final array, along with a list
+ of slices and a list of arrays that can be used for assignment inside the
+ new array
+
+ Parameters
+ ----------
+ arrays : nested list of arrays
+ The arrays to check
+ max_depth : list of int
+ The number of nested lists
+ result_ndim : int
+ The number of dimensions in thefinal array.
+
+ Returns
+ -------
+ shape : tuple of int
+ The shape that the final array will take on.
+ slices: list of tuple of slices
+ The slices into the full array required for assignment. These are
+ required to be prepended with ``(Ellipsis, )`` to obtain to correct
+ final index.
+ arrays: list of ndarray
+ The data to assign to each slice of the full array
+
+ """
+ if depth < max_depth:
+ shapes, slices, arrays = zip(
+ *[_block_info_recursion(arr, max_depth, result_ndim, depth+1)
+ for arr in arrays])
+
+ axis = result_ndim - max_depth + depth
+ shape, slice_prefixes = _concatenate_shapes(shapes, axis)
+
+ # Prepend the slice prefix and flatten the slices
+ slices = [slice_prefix + the_slice
+ for slice_prefix, inner_slices in zip(slice_prefixes, slices)
+ for the_slice in inner_slices]
+
+ # Flatten the array list
+ arrays = functools.reduce(operator.add, arrays)
+
+ return shape, slices, arrays
+ else:
+ # We've 'bottomed out' - arrays is either a scalar or an array
+ # type(arrays) is not list
+ # Return the slice and the array inside a list to be consistent with
+ # the recursive case.
+ arr = _atleast_nd(arrays, result_ndim)
+ return arr.shape, [()], [arr]
+
+
+def _block(arrays, max_depth, result_ndim, depth=0):
+ """
+ Internal implementation of block based on repeated concatenation.
+ `arrays` is the argument passed to
+ block. `max_depth` is the depth of nested lists within `arrays` and
+ `result_ndim` is the greatest of the dimensions of the arrays in
+ `arrays` and the depth of the lists in `arrays` (see block docstring
+ for details).
+ """
+ if depth < max_depth:
+ arrs = [_block(arr, max_depth, result_ndim, depth+1)
+ for arr in arrays]
+ return _concatenate(arrs, axis=-(max_depth-depth))
+ else:
+ # We've 'bottomed out' - arrays is either a scalar or an array
+ # type(arrays) is not list
+ return _atleast_nd(arrays, result_ndim)
+
+
+def _block_dispatcher(arrays):
+ # Use type(...) is list to match the behavior of np.block(), which special
+ # cases list specifically rather than allowing for generic iterables or
+ # tuple. Also, we know that list.__array_function__ will never exist.
+ if type(arrays) is list:
+ for subarrays in arrays:
+ yield from _block_dispatcher(subarrays)
+ else:
+ yield arrays
+
+
+@array_function_dispatch(_block_dispatcher)
+def block(arrays):
+ """
+ Assemble an nd-array from nested lists of blocks.
+
+ Blocks in the innermost lists are concatenated (see `concatenate`) along
+ the last dimension (-1), then these are concatenated along the
+ second-last dimension (-2), and so on until the outermost list is reached.
+
+ Blocks can be of any dimension, but will not be broadcasted using
+ the normal rules. Instead, leading axes of size 1 are inserted,
+ to make ``block.ndim`` the same for all blocks. This is primarily useful
+ for working with scalars, and means that code like ``np.block([v, 1])``
+ is valid, where ``v.ndim == 1``.
+
+ When the nested list is two levels deep, this allows block matrices to be
+ constructed from their components.
+
+ Parameters
+ ----------
+ arrays : nested list of array_like or scalars (but not tuples)
+ If passed a single ndarray or scalar (a nested list of depth 0), this
+ is returned unmodified (and not copied).
+
+ Elements shapes must match along the appropriate axes (without
+ broadcasting), but leading 1s will be prepended to the shape as
+ necessary to make the dimensions match.
+
+ Returns
+ -------
+ block_array : ndarray
+ The array assembled from the given blocks.
+
+ The dimensionality of the output is equal to the greatest of:
+
+ * the dimensionality of all the inputs
+ * the depth to which the input list is nested
+
+ Raises
+ ------
+ ValueError
+ * If list depths are mismatched - for instance, ``[[a, b], c]`` is
+ illegal, and should be spelt ``[[a, b], [c]]``
+ * If lists are empty - for instance, ``[[a, b], []]``
+
+ See Also
+ --------
+ concatenate : Join a sequence of arrays along an existing axis.
+ stack : Join a sequence of arrays along a new axis.
+ vstack : Stack arrays in sequence vertically (row wise).
+ hstack : Stack arrays in sequence horizontally (column wise).
+ dstack : Stack arrays in sequence depth wise (along third axis).
+ column_stack : Stack 1-D arrays as columns into a 2-D array.
+ vsplit : Split an array into multiple sub-arrays vertically (row-wise).
+ unstack : Split an array into a tuple of sub-arrays along an axis.
+
+ Notes
+ -----
+ When called with only scalars, ``np.block`` is equivalent to an ndarray
+ call. So ``np.block([[1, 2], [3, 4]])`` is equivalent to
+ ``np.array([[1, 2], [3, 4]])``.
+
+ This function does not enforce that the blocks lie on a fixed grid.
+ ``np.block([[a, b], [c, d]])`` is not restricted to arrays of the form::
+
+ AAAbb
+ AAAbb
+ cccDD
+
+ But is also allowed to produce, for some ``a, b, c, d``::
+
+ AAAbb
+ AAAbb
+ cDDDD
+
+ Since concatenation happens along the last axis first, `block` is *not*
+ capable of producing the following directly::
+
+ AAAbb
+ cccbb
+ cccDD
+
+ Matlab's "square bracket stacking", ``[A, B, ...; p, q, ...]``, is
+ equivalent to ``np.block([[A, B, ...], [p, q, ...]])``.
+
+ Examples
+ --------
+ The most common use of this function is to build a block matrix:
+
+ >>> import numpy as np
+ >>> A = np.eye(2) * 2
+ >>> B = np.eye(3) * 3
+ >>> np.block([
+ ... [A, np.zeros((2, 3))],
+ ... [np.ones((3, 2)), B ]
+ ... ])
+ array([[2., 0., 0., 0., 0.],
+ [0., 2., 0., 0., 0.],
+ [1., 1., 3., 0., 0.],
+ [1., 1., 0., 3., 0.],
+ [1., 1., 0., 0., 3.]])
+
+ With a list of depth 1, `block` can be used as `hstack`:
+
+ >>> np.block([1, 2, 3]) # hstack([1, 2, 3])
+ array([1, 2, 3])
+
+ >>> a = np.array([1, 2, 3])
+ >>> b = np.array([4, 5, 6])
+ >>> np.block([a, b, 10]) # hstack([a, b, 10])
+ array([ 1, 2, 3, 4, 5, 6, 10])
+
+ >>> A = np.ones((2, 2), int)
+ >>> B = 2 * A
+ >>> np.block([A, B]) # hstack([A, B])
+ array([[1, 1, 2, 2],
+ [1, 1, 2, 2]])
+
+ With a list of depth 2, `block` can be used in place of `vstack`:
+
+ >>> a = np.array([1, 2, 3])
+ >>> b = np.array([4, 5, 6])
+ >>> np.block([[a], [b]]) # vstack([a, b])
+ array([[1, 2, 3],
+ [4, 5, 6]])
+
+ >>> A = np.ones((2, 2), int)
+ >>> B = 2 * A
+ >>> np.block([[A], [B]]) # vstack([A, B])
+ array([[1, 1],
+ [1, 1],
+ [2, 2],
+ [2, 2]])
+
+ It can also be used in place of `atleast_1d` and `atleast_2d`:
+
+ >>> a = np.array(0)
+ >>> b = np.array([1])
+ >>> np.block([a]) # atleast_1d(a)
+ array([0])
+ >>> np.block([b]) # atleast_1d(b)
+ array([1])
+
+ >>> np.block([[a]]) # atleast_2d(a)
+ array([[0]])
+ >>> np.block([[b]]) # atleast_2d(b)
+ array([[1]])
+
+
+ """
+ arrays, list_ndim, result_ndim, final_size = _block_setup(arrays)
+
+ # It was found through benchmarking that making an array of final size
+ # around 256x256 was faster by straight concatenation on a
+ # i7-7700HQ processor and dual channel ram 2400MHz.
+ # It didn't seem to matter heavily on the dtype used.
+ #
+ # A 2D array using repeated concatenation requires 2 copies of the array.
+ #
+ # The fastest algorithm will depend on the ratio of CPU power to memory
+ # speed.
+ # One can monitor the results of the benchmark
+ # https://pv.github.io/numpy-bench/#bench_shape_base.Block2D.time_block2d
+ # to tune this parameter until a C version of the `_block_info_recursion`
+ # algorithm is implemented which would likely be faster than the python
+ # version.
+ if list_ndim * final_size > (2 * 512 * 512):
+ return _block_slicing(arrays, list_ndim, result_ndim)
+ else:
+ return _block_concatenate(arrays, list_ndim, result_ndim)
+
+
+# These helper functions are mostly used for testing.
+# They allow us to write tests that directly call `_block_slicing`
+# or `_block_concatenate` without blocking large arrays to force the wisdom
+# to trigger the desired path.
+def _block_setup(arrays):
+ """
+ Returns
+ (`arrays`, list_ndim, result_ndim, final_size)
+ """
+ bottom_index, arr_ndim, final_size = _block_check_depths_match(arrays)
+ list_ndim = len(bottom_index)
+ if bottom_index and bottom_index[-1] is None:
+ raise ValueError(
+ 'List at {} cannot be empty'.format(
+ _block_format_index(bottom_index)
+ )
+ )
+ result_ndim = max(arr_ndim, list_ndim)
+ return arrays, list_ndim, result_ndim, final_size
+
+
+def _block_slicing(arrays, list_ndim, result_ndim):
+ shape, slices, arrays = _block_info_recursion(
+ arrays, list_ndim, result_ndim)
+ dtype = _nx.result_type(*[arr.dtype for arr in arrays])
+
+ # Test preferring F only in the case that all input arrays are F
+ F_order = all(arr.flags['F_CONTIGUOUS'] for arr in arrays)
+ C_order = all(arr.flags['C_CONTIGUOUS'] for arr in arrays)
+ order = 'F' if F_order and not C_order else 'C'
+ result = _nx.empty(shape=shape, dtype=dtype, order=order)
+ # Note: In a c implementation, the function
+ # PyArray_CreateMultiSortedStridePerm could be used for more advanced
+ # guessing of the desired order.
+
+ for the_slice, arr in zip(slices, arrays):
+ result[(Ellipsis,) + the_slice] = arr
+ return result
+
+
+def _block_concatenate(arrays, list_ndim, result_ndim):
+ result = _block(arrays, list_ndim, result_ndim)
+ if list_ndim == 0:
+ # Catch an edge case where _block returns a view because
+ # `arrays` is a single numpy array and not a list of numpy arrays.
+ # This might copy scalars or lists twice, but this isn't a likely
+ # usecase for those interested in performance
+ result = result.copy()
+ return result
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/shape_base.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/shape_base.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..decb7be48f9e0cb2d8010bac2f494c5f43ea173c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/shape_base.pyi
@@ -0,0 +1,175 @@
+from collections.abc import Sequence
+from typing import Any, SupportsIndex, TypeVar, overload
+
+from numpy import _CastingKind, generic
+from numpy._typing import ArrayLike, DTypeLike, NDArray, _ArrayLike, _DTypeLike
+
+__all__ = [
+ "atleast_1d",
+ "atleast_2d",
+ "atleast_3d",
+ "block",
+ "hstack",
+ "stack",
+ "unstack",
+ "vstack",
+]
+
+_SCT = TypeVar("_SCT", bound=generic)
+_SCT1 = TypeVar("_SCT1", bound=generic)
+_SCT2 = TypeVar("_SCT2", bound=generic)
+_ArrayT = TypeVar("_ArrayT", bound=NDArray[Any])
+
+###
+
+@overload
+def atleast_1d(a0: _ArrayLike[_SCT], /) -> NDArray[_SCT]: ...
+@overload
+def atleast_1d(a0: _ArrayLike[_SCT1], a1: _ArrayLike[_SCT2], /) -> tuple[NDArray[_SCT1], NDArray[_SCT2]]: ...
+@overload
+def atleast_1d(a0: _ArrayLike[_SCT], a1: _ArrayLike[_SCT], /, *arys: _ArrayLike[_SCT]) -> tuple[NDArray[_SCT], ...]: ...
+@overload
+def atleast_1d(a0: ArrayLike, /) -> NDArray[Any]: ...
+@overload
+def atleast_1d(a0: ArrayLike, a1: ArrayLike, /) -> tuple[NDArray[Any], NDArray[Any]]: ...
+@overload
+def atleast_1d(a0: ArrayLike, a1: ArrayLike, /, *ai: ArrayLike) -> tuple[NDArray[Any], ...]: ...
+
+#
+@overload
+def atleast_2d(a0: _ArrayLike[_SCT], /) -> NDArray[_SCT]: ...
+@overload
+def atleast_2d(a0: _ArrayLike[_SCT1], a1: _ArrayLike[_SCT2], /) -> tuple[NDArray[_SCT1], NDArray[_SCT2]]: ...
+@overload
+def atleast_2d(a0: _ArrayLike[_SCT], a1: _ArrayLike[_SCT], /, *arys: _ArrayLike[_SCT]) -> tuple[NDArray[_SCT], ...]: ...
+@overload
+def atleast_2d(a0: ArrayLike, /) -> NDArray[Any]: ...
+@overload
+def atleast_2d(a0: ArrayLike, a1: ArrayLike, /) -> tuple[NDArray[Any], NDArray[Any]]: ...
+@overload
+def atleast_2d(a0: ArrayLike, a1: ArrayLike, /, *ai: ArrayLike) -> tuple[NDArray[Any], ...]: ...
+
+#
+@overload
+def atleast_3d(a0: _ArrayLike[_SCT], /) -> NDArray[_SCT]: ...
+@overload
+def atleast_3d(a0: _ArrayLike[_SCT1], a1: _ArrayLike[_SCT2], /) -> tuple[NDArray[_SCT1], NDArray[_SCT2]]: ...
+@overload
+def atleast_3d(a0: _ArrayLike[_SCT], a1: _ArrayLike[_SCT], /, *arys: _ArrayLike[_SCT]) -> tuple[NDArray[_SCT], ...]: ...
+@overload
+def atleast_3d(a0: ArrayLike, /) -> NDArray[Any]: ...
+@overload
+def atleast_3d(a0: ArrayLike, a1: ArrayLike, /) -> tuple[NDArray[Any], NDArray[Any]]: ...
+@overload
+def atleast_3d(a0: ArrayLike, a1: ArrayLike, /, *ai: ArrayLike) -> tuple[NDArray[Any], ...]: ...
+
+#
+@overload
+def vstack(
+ tup: Sequence[_ArrayLike[_SCT]],
+ *,
+ dtype: None = ...,
+ casting: _CastingKind = ...
+) -> NDArray[_SCT]: ...
+@overload
+def vstack(
+ tup: Sequence[ArrayLike],
+ *,
+ dtype: _DTypeLike[_SCT],
+ casting: _CastingKind = ...
+) -> NDArray[_SCT]: ...
+@overload
+def vstack(
+ tup: Sequence[ArrayLike],
+ *,
+ dtype: DTypeLike = ...,
+ casting: _CastingKind = ...
+) -> NDArray[Any]: ...
+
+@overload
+def hstack(
+ tup: Sequence[_ArrayLike[_SCT]],
+ *,
+ dtype: None = ...,
+ casting: _CastingKind = ...
+) -> NDArray[_SCT]: ...
+@overload
+def hstack(
+ tup: Sequence[ArrayLike],
+ *,
+ dtype: _DTypeLike[_SCT],
+ casting: _CastingKind = ...
+) -> NDArray[_SCT]: ...
+@overload
+def hstack(
+ tup: Sequence[ArrayLike],
+ *,
+ dtype: DTypeLike = ...,
+ casting: _CastingKind = ...
+) -> NDArray[Any]: ...
+
+@overload
+def stack(
+ arrays: Sequence[_ArrayLike[_SCT]],
+ axis: SupportsIndex = ...,
+ out: None = ...,
+ *,
+ dtype: None = ...,
+ casting: _CastingKind = ...
+) -> NDArray[_SCT]: ...
+@overload
+def stack(
+ arrays: Sequence[ArrayLike],
+ axis: SupportsIndex = ...,
+ out: None = ...,
+ *,
+ dtype: _DTypeLike[_SCT],
+ casting: _CastingKind = ...
+) -> NDArray[_SCT]: ...
+@overload
+def stack(
+ arrays: Sequence[ArrayLike],
+ axis: SupportsIndex = ...,
+ out: None = ...,
+ *,
+ dtype: DTypeLike = ...,
+ casting: _CastingKind = ...
+) -> NDArray[Any]: ...
+@overload
+def stack(
+ arrays: Sequence[ArrayLike],
+ axis: SupportsIndex,
+ out: _ArrayT,
+ *,
+ dtype: DTypeLike | None = None,
+ casting: _CastingKind = "same_kind",
+) -> _ArrayT: ...
+@overload
+def stack(
+ arrays: Sequence[ArrayLike],
+ axis: SupportsIndex = 0,
+ *,
+ out: _ArrayT,
+ dtype: DTypeLike | None = None,
+ casting: _CastingKind = "same_kind",
+) -> _ArrayT: ...
+
+@overload
+def unstack(
+ array: _ArrayLike[_SCT],
+ /,
+ *,
+ axis: int = ...,
+) -> tuple[NDArray[_SCT], ...]: ...
+@overload
+def unstack(
+ array: ArrayLike,
+ /,
+ *,
+ axis: int = ...,
+) -> tuple[NDArray[Any], ...]: ...
+
+@overload
+def block(arrays: _ArrayLike[_SCT]) -> NDArray[_SCT]: ...
+@overload
+def block(arrays: ArrayLike) -> NDArray[Any]: ...
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/strings.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/strings.py
new file mode 100644
index 0000000000000000000000000000000000000000..b751b5d773a0cc270d0e507eb3fba4a051b56508
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy/_core/strings.py
@@ -0,0 +1,1641 @@
+"""
+This module contains a set of functions for vectorized string
+operations.
+"""
+
+import sys
+import numpy as np
+from numpy import (
+ equal, not_equal, less, less_equal, greater, greater_equal,
+ add, multiply as _multiply_ufunc,
+)
+from numpy._core.multiarray import _vec_string
+from numpy._core.overrides import set_module
+from numpy._core.umath import (
+ isalpha,
+ isdigit,
+ isspace,
+ isalnum,
+ islower,
+ isupper,
+ istitle,
+ isdecimal,
+ isnumeric,
+ str_len,
+ find as _find_ufunc,
+ rfind as _rfind_ufunc,
+ index as _index_ufunc,
+ rindex as _rindex_ufunc,
+ count as _count_ufunc,
+ startswith as _startswith_ufunc,
+ endswith as _endswith_ufunc,
+ _lstrip_whitespace,
+ _lstrip_chars,
+ _rstrip_whitespace,
+ _rstrip_chars,
+ _strip_whitespace,
+ _strip_chars,
+ _replace,
+ _expandtabs_length,
+ _expandtabs,
+ _center,
+ _ljust,
+ _rjust,
+ _zfill,
+ _partition,
+ _partition_index,
+ _rpartition,
+ _rpartition_index,
+)
+
+
+def _override___module__():
+ for ufunc in [
+ isalnum, isalpha, isdecimal, isdigit, islower, isnumeric, isspace,
+ istitle, isupper, str_len,
+ ]:
+ ufunc.__module__ = "numpy.strings"
+ ufunc.__qualname__ = ufunc.__name__
+
+
+_override___module__()
+
+
+__all__ = [
+ # UFuncs
+ "equal", "not_equal", "less", "less_equal", "greater", "greater_equal",
+ "add", "multiply", "isalpha", "isdigit", "isspace", "isalnum", "islower",
+ "isupper", "istitle", "isdecimal", "isnumeric", "str_len", "find",
+ "rfind", "index", "rindex", "count", "startswith", "endswith", "lstrip",
+ "rstrip", "strip", "replace", "expandtabs", "center", "ljust", "rjust",
+ "zfill", "partition", "rpartition",
+
+ # _vec_string - Will gradually become ufuncs as well
+ "upper", "lower", "swapcase", "capitalize", "title",
+
+ # _vec_string - Will probably not become ufuncs
+ "mod", "decode", "encode", "translate",
+
+ # Removed from namespace until behavior has been crystallized
+ # "join", "split", "rsplit", "splitlines",
+]
+
+
+MAX = np.iinfo(np.int64).max
+
+
+def _get_num_chars(a):
+ """
+ Helper function that returns the number of characters per field in
+ a string or unicode array. This is to abstract out the fact that
+ for a unicode array this is itemsize / 4.
+ """
+ if issubclass(a.dtype.type, np.str_):
+ return a.itemsize // 4
+ return a.itemsize
+
+
+def _to_bytes_or_str_array(result, output_dtype_like):
+ """
+ Helper function to cast a result back into an array
+ with the appropriate dtype if an object array must be used
+ as an intermediary.
+ """
+ output_dtype_like = np.asarray(output_dtype_like)
+ if result.size == 0:
+ # Calling asarray & tolist in an empty array would result
+ # in losing shape information
+ return result.astype(output_dtype_like.dtype)
+ ret = np.asarray(result.tolist())
+ if isinstance(output_dtype_like.dtype, np.dtypes.StringDType):
+ return ret.astype(type(output_dtype_like.dtype))
+ return ret.astype(type(output_dtype_like.dtype)(_get_num_chars(ret)))
+
+
+def _clean_args(*args):
+ """
+ Helper function for delegating arguments to Python string
+ functions.
+
+ Many of the Python string operations that have optional arguments
+ do not use 'None' to indicate a default value. In these cases,
+ we need to remove all None arguments, and those following them.
+ """
+ newargs = []
+ for chk in args:
+ if chk is None:
+ break
+ newargs.append(chk)
+ return newargs
+
+
+@set_module("numpy.strings")
+def multiply(a, i):
+ """
+ Return (a * i), that is string multiple concatenation,
+ element-wise.
+
+ Values in ``i`` of less than 0 are treated as 0 (which yields an
+ empty string).
+
+ Parameters
+ ----------
+ a : array_like, with ``StringDType``, ``bytes_`` or ``str_`` dtype
+
+ i : array_like, with any integer dtype
+
+ Returns
+ -------
+ out : ndarray
+ Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
+ depending on input types
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array(["a", "b", "c"])
+ >>> np.strings.multiply(a, 3)
+ array(['aaa', 'bbb', 'ccc'], dtype='>> i = np.array([1, 2, 3])
+ >>> np.strings.multiply(a, i)
+ array(['a', 'bb', 'ccc'], dtype='>> np.strings.multiply(np.array(['a']), i)
+ array(['a', 'aa', 'aaa'], dtype='>> a = np.array(['a', 'b', 'c', 'd', 'e', 'f']).reshape((2, 3))
+ >>> np.strings.multiply(a, 3)
+ array([['aaa', 'bbb', 'ccc'],
+ ['ddd', 'eee', 'fff']], dtype='>> np.strings.multiply(a, i)
+ array([['a', 'bb', 'ccc'],
+ ['d', 'ee', 'fff']], dtype=' sys.maxsize / np.maximum(i, 1)):
+ raise MemoryError("repeated string is too long")
+
+ buffersizes = a_len * i
+ out_dtype = f"{a.dtype.char}{buffersizes.max()}"
+ out = np.empty_like(a, shape=buffersizes.shape, dtype=out_dtype)
+ return _multiply_ufunc(a, i, out=out)
+
+
+@set_module("numpy.strings")
+def mod(a, values):
+ """
+ Return (a % i), that is pre-Python 2.6 string formatting
+ (interpolation), element-wise for a pair of array_likes of str
+ or unicode.
+
+ Parameters
+ ----------
+ a : array_like, with `np.bytes_` or `np.str_` dtype
+
+ values : array_like of values
+ These values will be element-wise interpolated into the string.
+
+ Returns
+ -------
+ out : ndarray
+ Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
+ depending on input types
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array(["NumPy is a %s library"])
+ >>> np.strings.mod(a, values=["Python"])
+ array(['NumPy is a Python library'], dtype='>> a = np.array([b'%d bytes', b'%d bits'])
+ >>> values = np.array([8, 64])
+ >>> np.strings.mod(a, values)
+ array([b'8 bytes', b'64 bits'], dtype='|S7')
+
+ """
+ return _to_bytes_or_str_array(
+ _vec_string(a, np.object_, '__mod__', (values,)), a)
+
+
+@set_module("numpy.strings")
+def find(a, sub, start=0, end=None):
+ """
+ For each element, return the lowest index in the string where
+ substring ``sub`` is found, such that ``sub`` is contained in the
+ range [``start``, ``end``).
+
+ Parameters
+ ----------
+ a : array_like, with ``StringDType``, ``bytes_`` or ``str_`` dtype
+
+ sub : array_like, with `np.bytes_` or `np.str_` dtype
+ The substring to search for.
+
+ start, end : array_like, with any integer dtype
+ The range to look in, interpreted as in slice notation.
+
+ Returns
+ -------
+ y : ndarray
+ Output array of ints
+
+ See Also
+ --------
+ str.find
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array(["NumPy is a Python library"])
+ >>> np.strings.find(a, "Python")
+ array([11])
+
+ """
+ end = end if end is not None else MAX
+ return _find_ufunc(a, sub, start, end)
+
+
+@set_module("numpy.strings")
+def rfind(a, sub, start=0, end=None):
+ """
+ For each element, return the highest index in the string where
+ substring ``sub`` is found, such that ``sub`` is contained in the
+ range [``start``, ``end``).
+
+ Parameters
+ ----------
+ a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
+
+ sub : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
+ The substring to search for.
+
+ start, end : array_like, with any integer dtype
+ The range to look in, interpreted as in slice notation.
+
+ Returns
+ -------
+ y : ndarray
+ Output array of ints
+
+ See Also
+ --------
+ str.rfind
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array(["Computer Science"])
+ >>> np.strings.rfind(a, "Science", start=0, end=None)
+ array([9])
+ >>> np.strings.rfind(a, "Science", start=0, end=8)
+ array([-1])
+ >>> b = np.array(["Computer Science", "Science"])
+ >>> np.strings.rfind(b, "Science", start=0, end=None)
+ array([9, 0])
+
+ """
+ end = end if end is not None else MAX
+ return _rfind_ufunc(a, sub, start, end)
+
+
+@set_module("numpy.strings")
+def index(a, sub, start=0, end=None):
+ """
+ Like `find`, but raises :exc:`ValueError` when the substring is not found.
+
+ Parameters
+ ----------
+ a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
+
+ sub : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
+
+ start, end : array_like, with any integer dtype, optional
+
+ Returns
+ -------
+ out : ndarray
+ Output array of ints.
+
+ See Also
+ --------
+ find, str.index
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array(["Computer Science"])
+ >>> np.strings.index(a, "Science", start=0, end=None)
+ array([9])
+
+ """
+ end = end if end is not None else MAX
+ return _index_ufunc(a, sub, start, end)
+
+
+@set_module("numpy.strings")
+def rindex(a, sub, start=0, end=None):
+ """
+ Like `rfind`, but raises :exc:`ValueError` when the substring `sub` is
+ not found.
+
+ Parameters
+ ----------
+ a : array-like, with `np.bytes_` or `np.str_` dtype
+
+ sub : array-like, with `np.bytes_` or `np.str_` dtype
+
+ start, end : array-like, with any integer dtype, optional
+
+ Returns
+ -------
+ out : ndarray
+ Output array of ints.
+
+ See Also
+ --------
+ rfind, str.rindex
+
+ Examples
+ --------
+ >>> a = np.array(["Computer Science"])
+ >>> np.strings.rindex(a, "Science", start=0, end=None)
+ array([9])
+
+ """
+ end = end if end is not None else MAX
+ return _rindex_ufunc(a, sub, start, end)
+
+
+@set_module("numpy.strings")
+def count(a, sub, start=0, end=None):
+ """
+ Returns an array with the number of non-overlapping occurrences of
+ substring ``sub`` in the range [``start``, ``end``).
+
+ Parameters
+ ----------
+ a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
+
+ sub : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
+ The substring to search for.
+
+ start, end : array_like, with any integer dtype
+ The range to look in, interpreted as in slice notation.
+
+ Returns
+ -------
+ y : ndarray
+ Output array of ints
+
+ See Also
+ --------
+ str.count
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> c = np.array(['aAaAaA', ' aA ', 'abBABba'])
+ >>> c
+ array(['aAaAaA', ' aA ', 'abBABba'], dtype='>> np.strings.count(c, 'A')
+ array([3, 1, 1])
+ >>> np.strings.count(c, 'aA')
+ array([3, 1, 0])
+ >>> np.strings.count(c, 'A', start=1, end=4)
+ array([2, 1, 1])
+ >>> np.strings.count(c, 'A', start=1, end=3)
+ array([1, 0, 0])
+
+ """
+ end = end if end is not None else MAX
+ return _count_ufunc(a, sub, start, end)
+
+
+@set_module("numpy.strings")
+def startswith(a, prefix, start=0, end=None):
+ """
+ Returns a boolean array which is `True` where the string element
+ in ``a`` starts with ``prefix``, otherwise `False`.
+
+ Parameters
+ ----------
+ a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
+
+ prefix : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
+
+ start, end : array_like, with any integer dtype
+ With ``start``, test beginning at that position. With ``end``,
+ stop comparing at that position.
+
+ Returns
+ -------
+ out : ndarray
+ Output array of bools
+
+ See Also
+ --------
+ str.startswith
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> s = np.array(['foo', 'bar'])
+ >>> s
+ array(['foo', 'bar'], dtype='>> np.strings.startswith(s, 'fo')
+ array([True, False])
+ >>> np.strings.startswith(s, 'o', start=1, end=2)
+ array([True, False])
+
+ """
+ end = end if end is not None else MAX
+ return _startswith_ufunc(a, prefix, start, end)
+
+
+@set_module("numpy.strings")
+def endswith(a, suffix, start=0, end=None):
+ """
+ Returns a boolean array which is `True` where the string element
+ in ``a`` ends with ``suffix``, otherwise `False`.
+
+ Parameters
+ ----------
+ a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
+
+ suffix : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
+
+ start, end : array_like, with any integer dtype
+ With ``start``, test beginning at that position. With ``end``,
+ stop comparing at that position.
+
+ Returns
+ -------
+ out : ndarray
+ Output array of bools
+
+ See Also
+ --------
+ str.endswith
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> s = np.array(['foo', 'bar'])
+ >>> s
+ array(['foo', 'bar'], dtype='>> np.strings.endswith(s, 'ar')
+ array([False, True])
+ >>> np.strings.endswith(s, 'a', start=1, end=2)
+ array([False, True])
+
+ """
+ end = end if end is not None else MAX
+ return _endswith_ufunc(a, suffix, start, end)
+
+
+@set_module("numpy.strings")
+def decode(a, encoding=None, errors=None):
+ r"""
+ Calls :meth:`bytes.decode` element-wise.
+
+ The set of available codecs comes from the Python standard library,
+ and may be extended at runtime. For more information, see the
+ :mod:`codecs` module.
+
+ Parameters
+ ----------
+ a : array_like, with ``bytes_`` dtype
+
+ encoding : str, optional
+ The name of an encoding
+
+ errors : str, optional
+ Specifies how to handle encoding errors
+
+ Returns
+ -------
+ out : ndarray
+
+ See Also
+ --------
+ :py:meth:`bytes.decode`
+
+ Notes
+ -----
+ The type of the result will depend on the encoding specified.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> c = np.array([b'\x81\xc1\x81\xc1\x81\xc1', b'@@\x81\xc1@@',
+ ... b'\x81\x82\xc2\xc1\xc2\x82\x81'])
+ >>> c
+ array([b'\x81\xc1\x81\xc1\x81\xc1', b'@@\x81\xc1@@',
+ b'\x81\x82\xc2\xc1\xc2\x82\x81'], dtype='|S7')
+ >>> np.strings.decode(c, encoding='cp037')
+ array(['aAaAaA', ' aA ', 'abBABba'], dtype='>> import numpy as np
+ >>> a = np.array(['aAaAaA', ' aA ', 'abBABba'])
+ >>> np.strings.encode(a, encoding='cp037')
+ array([b'\x81\xc1\x81\xc1\x81\xc1', b'@@\x81\xc1@@',
+ b'\x81\x82\xc2\xc1\xc2\x82\x81'], dtype='|S7')
+
+ """
+ return _to_bytes_or_str_array(
+ _vec_string(a, np.object_, 'encode', _clean_args(encoding, errors)),
+ np.bytes_(b''))
+
+
+@set_module("numpy.strings")
+def expandtabs(a, tabsize=8):
+ """
+ Return a copy of each string element where all tab characters are
+ replaced by one or more spaces.
+
+ Calls :meth:`str.expandtabs` element-wise.
+
+ Return a copy of each string element where all tab characters are
+ replaced by one or more spaces, depending on the current column
+ and the given `tabsize`. The column number is reset to zero after
+ each newline occurring in the string. This doesn't understand other
+ non-printing characters or escape sequences.
+
+ Parameters
+ ----------
+ a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
+ Input array
+ tabsize : int, optional
+ Replace tabs with `tabsize` number of spaces. If not given defaults
+ to 8 spaces.
+
+ Returns
+ -------
+ out : ndarray
+ Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
+ depending on input type
+
+ See Also
+ --------
+ str.expandtabs
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array(['\t\tHello\tworld'])
+ >>> np.strings.expandtabs(a, tabsize=4) # doctest: +SKIP
+ array([' Hello world'], dtype='>> import numpy as np
+ >>> c = np.array(['a1b2','1b2a','b2a1','2a1b']); c
+ array(['a1b2', '1b2a', 'b2a1', '2a1b'], dtype='>> np.strings.center(c, width=9)
+ array([' a1b2 ', ' 1b2a ', ' b2a1 ', ' 2a1b '], dtype='>> np.strings.center(c, width=9, fillchar='*')
+ array(['***a1b2**', '***1b2a**', '***b2a1**', '***2a1b**'], dtype='>> np.strings.center(c, width=1)
+ array(['a1b2', '1b2a', 'b2a1', '2a1b'], dtype='>> import numpy as np
+ >>> c = np.array(['aAaAaA', ' aA ', 'abBABba'])
+ >>> np.strings.ljust(c, width=3)
+ array(['aAaAaA', ' aA ', 'abBABba'], dtype='>> np.strings.ljust(c, width=9)
+ array(['aAaAaA ', ' aA ', 'abBABba '], dtype='>> import numpy as np
+ >>> a = np.array(['aAaAaA', ' aA ', 'abBABba'])
+ >>> np.strings.rjust(a, width=3)
+ array(['aAaAaA', ' aA ', 'abBABba'], dtype='>> np.strings.rjust(a, width=9)
+ array([' aAaAaA', ' aA ', ' abBABba'], dtype='